python

python怎么继承父类方法下的属性

小亿
92
2024-05-22 09:27:10
栏目: 编程语言

在Python中,子类可以继承父类的属性和方法。如果你想在子类中使用父类的属性,可以使用super()函数来调用父类的方法并获取父类的属性。例如:

class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age

parent = Parent("Alice")
child = Child("Bob", 10)

print(parent.name)  # 输出:Alice
print(child.name)   # 输出:Bob
print(child.age)    # 输出:10

在上面的例子中,子类Child继承了父类Parent的属性name,并通过调用super().__init__(name)来初始化父类的属性。

0
看了该问题的人还看了