类的专有方法:
__init__ 构造函数,在生成对象时调用
__del__ 析构函数,释放对象时使用
__repr__ 打印,转换
__setitem__按照索引赋值
__getitem__按照索引获取值
__len__获得长度
__cmp__比较运算
__call__函数调用
__add__加运算
__sub__减运算
__mul__乘运算
__div__除运算
__mod__求余运算
__pow__称方
class BaseClass:
def __init__(self):
self.name = 'BaseClass'
print('BaseCalss: Constructor called')
def getname(self):
print('BaseCalss: self name equals ' + self.name)
class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
print('DerivedClass: Constructor called')
if __name__ == '__main__':
class1 = BaseClass()
class1.getname()
class2 = DerivedClass()
class2.getname()
运行结果:
BaseCalss: Constructor called BaseCalss: self name equals BaseClass BaseCalss: Constructor called DerivedClass: Constructor called BaseCalss: self name equals BaseClass
子类也可以overwrite父类的方法,那么父类的方法就不会被调用,除非手动调用:
class BaseClass:
def __init__(self):
self.name = 'BaseClass'
print('BaseCalss: Constructor called')
def getname(self):
print('BaseCalss: self name equals ' + self.name)
class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
print('DerivedClass: Constructor called')
def getname(self):
print('self.name init value is ' + self.name)
self.name = 'DerivedClass'
print('DerivedClass: self name equals ' + self.name)
if __name__ == '__main__':
class1 = BaseClass()
class1.getname()
class2 = DerivedClass()
class2.getname()
运行结果:
BaseCalss: Constructor called
BaseCalss: self name equals BaseClass
BaseCalss: Constructor called
DerivedClass: Constructor called
self.name init value is BaseClass
DerivedClass: self name equals DerivedClass
python不仅仅支持单继承,还支持多继承
class BaseClass1:
def __init__(self):
self.name1 = 'BaseClass1_Name1'
self.name = 'BaseClass1_Name'
print('BaseCalss1: Constructor called')
def getname1(self):
print('BaseCalss1: self name1 equals ' + self.name1)
def getname(self):
print('BaseCalss1: getname called, name equal ' + self.name)
class BaseClass2:
def __init__(self):
self.name2 = 'BaseClass2_Name2'
self.name = 'BaseClass2_Name'
print('BaseClass2: Constructor called')
def getname2(self):
print('BaseClass2: self name2 equals ' + self.name2)
def getname(self):
print('BaseCalss2: getname called, name equal ' + self.name)
class DerivedClass2(BaseClass1, BaseClass2):
def __init__(self):
BaseClass1.__init__(self)
BaseClass2.__init__(self)
print('DerivedClass: Constructor called')
if __name__ == '__main__':
class1 = BaseClass1()
class1.getname1()
class2 = BaseClass2()
class2.getname2()
class3 = DerivedClass2()
class3.getname1()
class3.getname2()
class3.getname()
运行结果:
BaseCalss1: Constructor called
BaseCalss1: self name1 equals BaseClass1_Name1
BaseClass2: Constructor called
BaseClass2: self name2 equals BaseClass2_Name2
BaseCalss1: Constructor called
BaseClass2: Constructor called
DerivedClass: Constructor called
BaseCalss1: self name1 equals BaseClass1_Name1
BaseClass2: self name2 equals BaseClass2_Name2
BaseCalss1: getname called, name equal BaseClass2_Name