类-python
super
super()
是继承父类,那么super().__init__()
代表不用实例化就可以调用父类的__init__()
方法来对子类进行初始化,那么这就相当于我们实例化了一个对象,那当然需要给super().__init__()
指定它的参数了
super() 里面可以不加参数,也可以加2个参数(旧写法,放弃)。如果加2个参数: 第一个是子类,第二个参数是该子类实例的对象。
class Rectangle:def __init__(self, length, width):self.length = lengthself.width = widthdef area(self):return self.length * self.widthclass Square(Rectangle):def __init__(self, length):super(Square, self).__init__(length, length)
super().__init__(*args, **kwargs)
使用*args
和**kwargs
可以让子类接受任意数量的位置参数和关键字参数,并将它们传递给父类。
class Car(object):def __init__(self, owner, year, model):self.owner = ownerself.year = yearself.model = model def get_info(self):"""打印车辆信息"""print(f'The owner of the car is {self.owner}\n' \f'The model of the car is {self.year}-{self.model}')
class ElectricalCar(Car):def __init__(self, battery, *args):super().__init__(*args) # 将剩下的参数打包送给superself.battery = battery # 从参数列表中拿出battery初始化子类属性def get_power(self):"""打印电池信息"""print(f'The battery of this car is {self.battery}')
tesla = ElectricalCar('10000kwh','Jarry', 2021, 'Model S')
tesla.get_info()
tesla.get_power()
The owner of the car is Jarry
The model of the car is 2021-Model S
The battery of this car is 10000kwh
单个继承
class Parent:def __init__(self, name):self.name = nameclass Child(Parent):def __init__(self, name, age):super().__init__(name) # Call parent's constructor firstself.age = ageparent = Parent("Alice")
child = Child("Bob", 12)print("Parent:", parent.name)
print("Child:", child.name, child.age)
Parent: Alice Child: Bob 12
Multiple Inheritance
class Base1:def __init__(self, x):self.x = xclass Base2:def __init__(self, y):self.y = yclass Derived(Base1, Base2):def __init__(self, x, y, z):super().__init__(x) # Call first base class constructor# Call second base class constructor explicitlyBase2.__init__(self, y)self.z = zderived = Derived(1, 2, 3)print("Derived:", derived.x, derived.y, derived.z)
Output
Derived: 1 2 3
Multi-Level Inheritance
class Grandparent:def __init__(self, name):self.name = nameclass Parent(Grandparent):def __init__(self, name, age):super().__init__(name) # Call grandparent's constructorself.age = ageclass Child(Parent):def __init__(self, name, age, hobby):super().__init__(name, age) # Call parent's constructorself.hobby = hobbychild = Child("Charlie", 8, "reading")print("Child:", child.name, child.age, child.hobby)
Output
Child: Charlie 8 reading