zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python(11):类

Python 11
2023-09-14 09:14:55 时间

目录

0. 相关文章链接

1. 创建类

2. 类的具体使用

2.1. 直接使用

2.2. 通过方法使用

2.3. 对象的基本信息方法

3. 继承


0. 相关文章链接

 Python文章汇总 

1. 创建类

class people:
    '帮助信息:XXXXXX'
    #所有实例都会共享
    number = 100
    #构造函数,初始化的方法,当创建一个类的时候,首先会调用它
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def display(self):
        print ('number = ',people.number)
    def display_name(self):
        print (self.name)

2. 类的具体使用

2.1. 直接使用

2.2. 通过方法使用

2.3. 对象的基本信息方法

print (people.__doc__)
print (people.__name__)
print (people.__module__)
print (people.__bases__)
print (people.__dict__)
帮助信息:XXXXXX
people
__main__
(<class 'object'>,)
{'__module__': '__main__', '__doc__': '帮助信息:XXXXXX', 'number': 100, '__init__': <function people.__init__ at 0x000001E0E9DB5700>, 'display': <function people.display at 0x000001E0E9DB5790>, 'display_name': <function people.display_name at 0x000001E0E9DB5820>, '__dict__': <attribute '__dict__' of 'people' objects>, '__weakref__': <attribute '__weakref__' of 'people' objects>}

3. 继承

class Parent: #定义父类
    number = 100
    def __init__(self):
        print ('调用父类构造函数')
    def parentM(self):
        print ('调用父类方法')
    def setAttr(self,attr):
        Parent.parentAttr = attr
    def getAttr(self):
        print ('父类属性:',Parent.parentAttr)
    def newM(self):
        print ('父类要被重新的方法')
        
class child(Parent): #定义子类
    def __init__(self):
        print ('调用子类构造函数')
    def childM(self):
        print ('调用子类方法')
    def newM(self):
        print ('子类给它改掉了') 
        
c = child()
c.childM()
c.parentM()
c.setAttr(100)
c.getAttr()
c.newM()
调用子类构造函数
调用子类方法
调用父类方法
父类属性: 100
子类给它改掉了
  • 通过子类创建对象,会调用子类的构造函数
  • 调用子类的方法,会执行子类方法中的代码
  • 调用父类的方法,因为子类已经继承了,所以还是执行父类方法中的代码
  • 设置属性时,因为子类已经继承了,所以还是执行父类方法中的代码,进行属性赋值
  • 获取属性时,因为子类已经继承了,所以还是执行父类方法中的代码,进行属性获取
  • 当调用子类中重写的方法时,会执行子类方法中的代码

注:其他Python相关系列文章链接由此进 ->   Python文章汇总