创建一个类,初始化类实例时就会自动执行__init__()方法。该方法的第一个参数为self,表示的就是类的实例。self后面跟随的其他参数就是创建类实例时要传入的参数。
class LogicGate:
def __init__(self, n):
self.label = n
self.output = None
g1 = LogicGate("G1")
g2 = LogicGate("G2")
# 测试:
>>> g1 = LogicGate("G1")
>>> g2 = BinaryGate("G2")
>>> g1
<__main__.LogicGate object at 0x00000246713B8B00>
>>> g2
<__main__.BinaryGate object at 0x00000246713B8AC8>
>>> g1.label
'G1'
>>> g2.output
g1,g2都是类实例,从最后g1.label和g2.output可以得知,实例化类LogicGate和BinaryGate时执行了__init__()方法。
子类继承父类的构造器时,会先执行父类构造器,再执行子类的:
class Transport:
def __init__(self, speed):
self.speed = speed
print('the speed of class Transport is' + self.speed)
class TransType(Transport):
def __init__(self, speed, ttype):
super(TransType, self).__init__(speed)
self.ttype = ttype
print('the type of TransType is' + self.ttype)
class TransBrand(TransType):
def __init__(self, speed, ttype, brand):
TransType.__init__(self, speed, ttype)
self.brand = brand
print('the brand of TransBrand is' + self.brand)
# 测试:
>>> car1 = TransBrand('50', 'car', 'dazhong')
the speed of class Transport is50
the type of TransType iscar
the brand of TransBrand isdazhong
注意上面代码中子类的构造器写法:调用父类的部分传入和父类相关的参数,然后再写子类自己特殊的部分。