如果希望在子类中不调用父类的__init__方法,可以在子类的__init__方法中显式地不调用super()。 ```python class Parent: def __init__(self): print("Parent class __init__") class Child(Parent): def __init__(self): print("Child class __init
子类的init方法被调用 在上面的示例中,子类ChildClass继承自父类ParentClass,并且重写了父类的init方法。在子类的init方法中,我们使用super().init()来调用父类的init方法。这样,在创建子类对象时,父类的init方法会被先调用,然后再调用子类的init方法。 这种调用方式的优势在于,我们可以在子类中扩展父类的功能,而...
child = Child() # 输出:Parent class __init__ ``` 2. 在子类中不调用父类的__init__方法 如果希望在子类中不调用父类的__init__方法,可以在子类的__init__方法中显式地不调用super()。 ```python class Parent: def __init__(self): print("Parent class __init__") class Child(Parent)...
classParent:def__init__(self,name):self.name=nameclassChild(Parent):def__init__(self,name,age):super().__init__(name)self.age=age parent=Parent("John")child=Child("Alice",10)print(parent.name)# 输出:Johnprint(child.name)# 输出:Aliceprint(child.age)# 输出:10 1. 2. 3. 4. 5....
classParent:def__init__(self,name):self.name=name 1. 2. 3. 在这里,我们定义了一个名为Parent的类,并在__init__方法中接受一个参数name并将其赋值给实例的name属性。 步骤2:创建子类并继承父类 接下来,我们创建一个子类并继承父类的属性和方法,示例代码如下: ...
class People: # 类属性 sex = 'nan' # 构造函数:魔术方法 def __init__(self, name, age): # 实例化属性 self.name = name # self代表对象本身 self.age = age # 实例化方法 def sleep(self): self.aa = 1 print('{}正在睡觉,性别为{}'.format(self.name, People.sex)) ...
class ChildClass(ParentClass): def __init__(self, attr4, attr5):super().__init__("value1", "value2", "value3") self.attr4 = attr4 self.attr5 = attr5 child = ChildClass("value4", "value5") 在上述代码中,父类ParentClass有3个实例属性attr1、attr2和attr3,子类ChildClass有2个实...
self.__private = 1 # 实际是 _Parent__private class Child(Parent): definit(self): super().init() self.__private = 2 # 实际是 _Child__private(不会覆盖父类的属性) 并非真正的私有:Python没有严格的私有属性,名称改写只是约定性的保护机制。
classParent:def__init__(self):print('This is parent init.')defsleep(self):print("Parent sleeps.")classChild(Parent):def__init__(self):#Parent.__init__(self)super(Child,self).__init__()print('This is child init.')defsleep(self):print("Child sleeps.") ...
classParent1:def__init__(self):self.value =1classParent2:def__init__(self):self.value =2classChild(Parent1,Parent2):def__init__(self):super().__init__()# 调用第一个父类的初始化方法self.new_value =3child = Child()print(child.value)# 输出1,即来自Parent1的valueprint(child.new_...