python的方法重写
时间: 2023-10-15 08:23:26 浏览: 46
方法重写是指在子类中重新定义父类中已经存在的方法。通过方法重写,子类可以改变继承的方法的行为,使其适应子类的特定需求。
在Python中,方法重写非常简单。只需在子类中定义与父类中同名的方法,并在其中实现子类自己的逻辑即可。例如:
```python
class Parent:
def say_hello(self):
print("Hello from parent")
class Child(Parent):
def say_hello(self):
print("Hello from child")
p = Parent()
p.say_hello() # 输出: Hello from parent
c = Child()
c.say_hello() # 输出: Hello from child
```
在上述例子中,父类`Parent`中有一个名为`say_hello`的方法,子类`Child`中也定义了一个同名的方法。当我们调用`say_hello`时,会根据实例的类型来决定使用哪个方法。因此,`p.say_hello()`调用的是父类中的方法,而`c.say_hello()`调用的是子类中重写的方法。
需要注意的是,子类重写父类方法时,方法名、参数个数、参数类型等需保持一致,否则会导致方法重载(overloading)而不是重写。
相关问题
Python方法重写
以下是Python方法重写的几种方法:
1. 在子类中重新定义和父类同名的方法
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def override_method(self):
print("This is the child class method")
child = ChildClass()
child.override_method() # 输出:This is the child class method
```
2. 在子类代码中,使用super().方法名()调用父类中的功能
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def override_method(self):
super().override_method()
print("This is the additional functionality in the child class method")
child = ChildClass()
child.override_method() # 输出:This is the parent class method This is the additional functionality in the child class method
```
3. 书写新的功能
```python
class ParentClass:
def override_method(self):
print("This is the parent class method")
class ChildClass(ParentClass):
def new_method(self):
print("This is a new method in the child class")
child = ChildClass()
child.override_method() # 输出:This is the parent class method
child.new_method() # 输出:This is a new method in the child class
```
python方法重写
Python中的方法重写是指在子类中重新定义父类中已经存在的方法。通过重写方法,子类可以对继承自父类的方法进行定制化修改,以满足子类自身的特殊需求。
要重写一个方法,子类需要定义与父类中方法名相同的方法,并在该方法中实现自己的逻辑。在调用该方法时,Python会先在子类中查找是否有该方法的定义,如果有则执行子类的方法,而不会调用父类中的同名方法。
下面是一个简单的示例:
```
class Animal:
def sound(self):
print("Animal makes a sound.")
class Dog(Animal):
def sound(self):
print("Dog barks.")
animal = Animal()
animal.sound() # 输出: Animal makes a sound.
dog = Dog()
dog.sound() # 输出: Dog barks.
```
在上面的例子中,父类`Animal`定义了一个`sound`方法,子类`Dog`重写了该方法并给出了不同的实现。当我们分别创建`Animal`和`Dog`对象并调用`sound`方法时,输出结果分别是父类和子类中定义的内容。
这就是Python中的方法重写。注意,在子类中重写方法时,可以使用`super()`函数调用父类中的同名方法,以便在子类中保留父类方法的功能。