如何在Python中访问父类属性?

如何在Python中访问父类属性?

In object-oriented programming, inheritance allows us to create new classes that inherit the properties and methods of an existing class. This powerful concept enables code reuse, modularity, and extensibility in our programs. Before diving into accessing parent class attributes, let's have a quick refresher on inheritance. In Python, when a class inherits from another class, it acquires all the attributes and methods defined in the parent class. This mechanism allows us to create specialized classes that inherit and extend the functionality of a more general base class. The derived class is also known as a child class, while the class being inherited from is called the parent class or base class.

Example

这里有一个简单的示例来说明继承的概念 -

class Parent: def __init__(self): self.parent_attribute = "I'm from the parent class" class Child(Parent): def __init__(self): super().__init__() self.child_attribute = "I'm from the child class" child = Child() print(child.parent_attribute) # Accessing parent class attribute print(child.child_attribute) 登录后复制