Linux 拨号vps windows公众号手机端

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

lewis 1年前 (2024-05-17) 阅读数 14 #程序编程
文章标签 python

在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)来初始化父类的属性。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门