---恢复内容开始---
1 class Turtle: 2 def __init__(self, x): 3 self.num = x 4 5 class Fish: 6 def __init__(self, x): 7 self.num = x 8 9 class Pool: 10 def __init__(self, x, y): 11 self.turtle = Turtle(x) #类的实例放在新类里 12 self.fish = Fish(y) 13 14 def print_num(self): 15 print("水池里总共有乌龟 %d 只,小鱼 %d 条!" % (self.turtle.num, self.fish.num))
>>> pool = Pool(1,10) >>> pool.print_num() 水池里总共有乌龟1只,小鱼10条! >>>
组合:把类的实例化放在新类里,把旧类组合成新的类
Mix-in(扩展阅读)
类,类对象和实例对象
>>> a = C() >>> b = C() >>> a.count 0 >>> b.count 0 >>> C.count 0 >>> a.count += 10 >>> a.count 10 >>> b.count 0 >>> C.count += 100 >>> C.count 100 >>> a.count 10 >>> b.count 100
因为a用了count,那就覆盖了类对象提供的属性
如果属性和方法名称相同,会覆盖掉方法
>>> class C: def x(self): print("X-man") >>> c = C() >>> c.x() X-man >>> c.x = 1 #创建一个x属性 >>> c.x 1 >>> c.x() Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> c.x() TypeError: 'int' object is not callable
不要试图在一个类里面定义出所有能想到的特性和方法,应该利用继承和组合机制来进行拓展。
用不同的词性命名,如属性名用名次,方法名用动词
绑定:定义类的方法时,要加self,创建实例化对象时才能调用该方法
---恢复内容结束---