在子类中添加实例属性可以通过以下步骤实现:
super()
函数调用父类的构造函数,以便继承父类的属性和方法。以下是一个示例代码:
class ParentClass:
def __init__(self, parent_property):
self.parent_property = parent_property
def parent_method(self):
print("This is a parent method.")
class ChildClass(ParentClass):
def __init__(self, parent_property, child_property):
super().__init__(parent_property)
self.child_property = child_property
def child_method(self):
print("This is a child method.")
# 创建子类的实例
child = ChildClass("Parent Property", "Child Property")
# 访问父类的属性和方法
print(child.parent_property)
child.parent_method()
# 访问子类的属性和方法
print(child.child_property)
child.child_method()
在这个示例中,ParentClass
是父类,它有一个属性parent_property
和一个方法parent_method
。ChildClass
是子类,它继承了父类的属性和方法,并添加了一个属性child_property
和一个方法child_method
。在子类的构造函数中,使用super().__init__()
调用父类的构造函数,以便继承父类的属性。然后,在子类中定义自己的属性child_property
。
这样,我们就可以在子类中添加实例属性了。
领取专属 10元无门槛券
手把手带您无忧上云