父类是在函数里面创建的对象,子类如何调用
时间: 2024-03-16 16:42:33 浏览: 21
如果你想在子类中使用父类的属性或方法,可以使用 `super()` 函数来调用父类。在子类中,你可以通过 `super()` 函数来访问父类的方法和属性,例如:
```python
class Parent:
def __init__(self):
self.parent_property = "I am a parent"
def parent_method(self):
print("I am a parent method")
class Child(Parent):
def __init__(self):
super().__init__() # 调用父类的构造函数
self.child_property = "I am a child"
def child_method(self):
print("I am a child method")
child = Child()
print(child.parent_property) # 访问父类的属性
child.parent_method() # 调用父类的方法
```
在上面的例子中,`Child` 类继承了 `Parent` 类,并通过 `super()` 函数调用了 `Parent` 类的构造函数。在 `Child` 类中,你也可以使用 `super()` 函数来调用 `Parent` 类的方法和属性。