您的位置:首页 > 科技 > IT业 > 智邦国际erp系统_苏州关键词优化软件_百度搜索排名优化哪家好_刷外链

智邦国际erp系统_苏州关键词优化软件_百度搜索排名优化哪家好_刷外链

2025/4/29 16:09:18 来源:https://blog.csdn.net/xihuanniNI/article/details/147562747  浏览:    关键词:智邦国际erp系统_苏州关键词优化软件_百度搜索排名优化哪家好_刷外链
智邦国际erp系统_苏州关键词优化软件_百度搜索排名优化哪家好_刷外链

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com