84-OOP之组合
2018-08-02 本文已影响2人
凯茜的老爸
如果两个类有本质不同,其中一类的对象是另一个类对象的组件时,使用组合是最佳方案。
玩具熊还有生产厂商的信息,生产厂商的信息可以作为玩具熊的一个属性。
class Vendor:
def __init__(self, phone, email):
self.phone = phone
self.email = email
def call(self):
print('calling %s' % self.phone)
class BearToy:
def __init__(self, color, size, phone, email):
self.color = color # 绑定属性到实例
self.size = size
self.vendor = Vendor(phone, email)
if __name__ == '__main__':
bigbear = BearToy('Brown', 'Middle', '400-111-8989', 'sales@tedu.cn')
print(bigbear.color)
bigbear.vendor.call()