Python系列:__init__()构造器,类的继承

创建一个类,初始化类实例时就会自动执行__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

注意上面代码中子类的构造器写法:调用父类的部分传入和父类相关的参数,然后再写子类自己特殊的部分。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值