|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1.组合可以用于把不同的类结合在一起。例如一个池塘(类A)中有各种水生植物鱼(类B)、乌龟(类C)、青蛙(类D)等。
如下:
- // 乌龟类
- class Turtle:
- def __init__(self, x):
- self.num = x
- // 鱼类
- class Fish:
- def __init__(self, x):
- self.num = x
- // 水池类
- class Pool:
- def __init__(self, x, y):
- self.turtle = Turtle(x) // 组合乌龟类进来
- self.fish = Fish(y) // 组合鱼类进来
-
- def print_num(self):
- print("水池里总共有乌龟 %d 只,小鱼 %d 条!" % (self.turtle.num, self.fish.num))
- >>> pool = Pool(1, 10)
- >>> pool.print_num()
复制代码
2.一个类定义完之前叫类的定义,定义完之后叫类对象,被引用后叫实例对象。
如果对象的属性与方法名相同,属性会覆盖方法。
如下:
- class C:
- def x(self):
- print('Xman')
- >>> c = C()
- >>> c.x()
- Xman
- >>> c.x = 1
- >>> c.x
- 1
- >>> c.x()
- Traceback (most recent call last):
- File "<pyshell#20>", line 1, in <module>
- c.x()
- TypeError: 'int' object is not callable
复制代码
|
评分
-
查看全部评分
|