|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 继承机制可以减少代码量, 其中如果一个类A继承来自另一个类B, 则称A为B的子类, B为A的父类, 继承可以使子类具有父类的各种方法和属性, 在继承时, 可以重新定义某种属性或重写某种方法来覆盖父类原有的属性或方法, 使其获得和父类不同的功能, 例如:
- >>> class Parent:
- def hello(self):
- print("正在调用父类...")
-
- >>> class Child(Parent):
- pass
- >>> p = Parent()
- >>> p.hello()
- 正在调用父类...
- >>> c = Child()
- >>> c.hello()
- 正在调用父类...
- >>> class Child(Parent):
- def hello(self):
- print("正在调用子类的方法...")
复制代码
2. 对于 __init__ , 返回为None, 不能返回除了None以外的对象
3. 对于子类继承父类并覆盖相应的属性或方法, 例如:
- import random as r
- class Fish:
- def __init__(self):
- self.x = r.randint(0, 10)
- self.y = r.randint(0, 10)
- def move(self):
- self.x -= 1
- print("我的位置是: ", self.x, self.y)
- class Goldfish(Fish):
- pass
- class Carp(Fish):
- pass
- class Salmon(Fish):
- pass
- class Shark(Fish):
- def __init__(self):
- super().__init__()
- self.hungry = True
- def eat(self):
- if self.hungry:
- print("吃吃吃")
- self.hungry = False
- else:
- print("吃饱了")
复制代码
4. super(): 在想要继承原有的__init__方法并进行修改时, 在子类的 __init__ 内使用 super().__init__() 即可保留原有的内容
5. 多重继承(钻石继承, 菱形继承): 可以同时继承多个类, 但有缺点, 尽量不要使用
|
|