python继承类方法
时间: 2023-08-27 14:16:04 浏览: 54
在Python中,继承类方法可以通过在子类中定义同名的方法来实现。子类可以继承父类的方法并且可以重写父类的方法。当子类调用这个方法时,会优先调用子类中的方法。
下面是一个简单的示例代码,演示了如何在子类中继承父类的方法:
```python
class ParentClass:
def method(self):
print("This is a method from the parent class.")
class ChildClass(ParentClass):
pass
obj = ChildClass()
obj.method()
```
输出结果为:
```
This is a method from the parent class.
```
在上面的示例中,`ParentClass` 是父类,而 `ChildClass` 是子类。子类 `ChildClass` 并没有定义自己的 `method` 方法,所以它继承了父类 `ParentClass` 中的 `method` 方法。
如果你想在子类中重写父类的方法,可以在子类中定义一个同名的方法,并在其中实现子类自己的逻辑。例如:
```python
class ParentClass:
def method(self):
print("This is a method from the parent class.")
class ChildClass(ParentClass):
def method(self):
print("This is a method from the child class.")
obj = ChildClass()
obj.method()
```
输出结果为:
```
This is a method from the child class.
```
在上面的示例中,子类 `ChildClass` 重写了父类 `ParentClass` 中的 `method` 方法,并实现了自己的逻辑。当子类对象调用 `method` 方法时,会优先调用子类中的方法。