python ,如何指定调用父类的方法
时间: 2023-06-03 20:06:12 浏览: 50
您可以在子类中使用super()函数来调用父类的方法,例如:
class Parent:
def say_hello(self):
print("Hello from parent")
class Child(Parent):
def say_hello(self):
super().say_hello() # 调用父类的方法
print("Hello from child")
c = Child()
c.say_hello() # 输出 "Hello from parent" 和 "Hello from child"
相关问题
python子类调用父类属性
在Python中,子类可以通过`super()`函数来调用父类的属性。具体的方法是在子类的初始化函数`__init__()`中调用`super().__init__()`来调用父类的初始化函数,从而获得父类的属性。例如:
```python
class Parent:
def __init__(self):
self.parent_property = "I am from Parent class"
class Child(Parent):
def __init__(self):
super().__init__()
self.child_property = "I am from Child class"
child = Child()
print(child.parent_property)
```
在这个例子中,子类`Child`继承了父类`Parent`,并且在子类的初始化函数中调用了父类的初始化函数,从而获得了父类的属性`parent_property`。最后,我们通过`print(child.parent_property)`打印出了子类的父类属性。
python调用父类的构造方法
在 Python 中,可以使用 `super()` 函数来调用父类的构造方法,如下示例:
```
class ParentClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
class ChildClass(ParentClass):
def __init__(self, arg1, arg2, arg3):
super().__init__(arg1, arg2)
self.arg3 = arg3
child = ChildClass('a', 'b', 'c')
print(child.arg1, child.arg2, child.arg3) # Output: a b c
```
在上述示例中,`ChildClass` 继承自 `ParentClass`,并且覆盖了父类的构造方法。在 `ChildClass` 的构造方法中,通过调用 `super().__init__(arg1, arg2)` 来调用父类的构造方法,并将 `arg1` 和 `arg2` 传递给它。这样,我们就可以在子类构造函数中同时获得父类和子类的属性。