单继承
class Parent:
def __init__(self):
self.parent_attribute = "I am a parent attribute"
def parent_method(self):
print("This is a method from the parent class")
class Child(Parent):
def __init__(self):
super().__init__() 调用父类的构造方法
self.child_attribute = "I am a child attribute"
def child_method(self):
print("This is a method from the child class")
child_instance = Child()
print(child_instance.parent_attribute) 输出: I am a parent attribute
child_instance.parent_method() 输出: This is a method from the parent class
多继承
class Master:
def __init__(self):
self.skill = "炒菜"
def showSkill(self):
print(self.skill)
class Bagger:
def __init__(self):
self.skill = "乞讨"
def showSkill(self):
print(self.skill)
class Man(Master, Bagger):
pass
man = Man()
man.showSkill() 输出: 炒菜
重写父类方法
class Parent:
def __init__(self):
self.name = "Parent"
def hello(self):
print("Hello from Parent")
class Child(Parent):
def hello(self):
print("Hello from Child")
child = Child()
child.hello() 输出: Hello from Child
使用`super()`调用父类方法
class Parent:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, my name is {self.name}")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name)
self.age = age
def greet(self):
super().greet()
print(f"I am {self.age} years old")
child = Child("Alice", 30)
child.greet() 输出: Hello, my name is Alice I am 30 years old
继承允许子类重用父类的属性和方法,并且可以添加新的属性和方法或者重写父类的方法。使用`super()`函数可以在子类的方法中调用父类的实现,这在重写方法时尤其有用