被继承的类称为基类、父类或超类;继承者称为子类,一个子类可以继承它的父类的任何属性和方法。举个例子:
# 类名大写,方法名小写,约定俗称
class Parent:
def hello(self):
print("using parent's class...")
class Child(Parent):
pass
p = Parent()
p.hello()
using parent's class...
c = Child()
c.hello()
using parent's class...
- 子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法
继承
例子:
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("my seat: ", self.x, self.y)
# 子类
Class Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print("i want eat...")
self.hungry = False
else:
print("I am full, don't eat...")
shark = Shark()
shark.move()
Trackback (most recent call last):
AttributeError: 'Shark' object has no attribute 'x'
# 原因:在shark类中,重写了__init__()方法,但是新的__init__()方法里没有初始化父类的属性(这里是x,y),因此调用move方法就会出错。结局方法:使用super函数
class Shark(Fish):
def __init__(self):
super().__init__()
...
本文探讨了面向对象编程中的类继承概念,解释了基类、父类与子类的关系,以及子类如何通过方法覆盖来修改或扩展父类的行为。通过具体的Python代码示例,展示了如何创建基类和子类,以及如何正确地在子类中初始化父类的属性,避免常见的错误。

367

被折叠的 条评论
为什么被折叠?



