Python中子类可以通过继承父类来继承父类的属性。可以使用 super() 函数来调用父类的构造函数,从而继承父类的属性。以下是一个示例代码:
class ParentClass: def __init__(self, attribute): self.attribute = attributeclass ChildClass(ParentClass): def __init__(self, attribute, child_attribute): super().__init__(attribute) # 调用父类的构造函数 self.child_attribute = child_attributeparent = ParentClass("Parent Attribute")child = ChildClass("Parent Attribute", "Child Attribute")print(parent.attribute) # 输出 "Parent Attribute"print(child.attribute) # 输出 "Parent Attribute"print(child.child_attribute) # 输出 "Child Attribute"在上面的代码中,ParentClass 是父类,ChildClass 是子类。子类 ChildClass 继承了父类 ParentClass 的属性 attribute。在子类的构造函数中,我们使用 super().__init__(attribute) 来调用父类的构造函数并初始化父类的属性。然后,我们还可以在子类中定义自己的属性,如 child_attribute。最后,我们创建父类实例 parent 和子类实例 child,并分别访问它们的属性。

