python中类方法重写_Python中的方法重写
python中类方法重写
Python中的方法重写 (Method Overriding in Python)
Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in the child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method which is already provided by one of its parent class(ancestors).
方法重写是面向对象编程的概念,它允许我们更改父类中定义的子类中函数的实现。 子类具有更改其父类(祖先)之一已提供的任何方法的实现的能力。
Following conditions must be met for overriding a function:
覆盖功能必须满足以下条件:
- Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent class.继承应该在那里。 函数重写不能在类内完成。 我们需要从父类派生子类。
- number of parameters.参数数量相同。
As we have already learned about the concept of Inheritance, we know that when a child class inherits a parent class it also get access to it public
and protected
(access modifiers in python) variables and methods, for example,
正如我们已经了解了继承的概念一样 ,我们知道,当子类继承父类时,它也可以访问它的public
和protected
变量和方法(例如python中的访问修饰符 ),
# parent class
class Parent:
# some random function
def anything(self):
print('Function defined in parent class!')
# child class
class Child(Parent):
# empty class definition
pass
obj2 = Child()
obj2.anything()
Function defined in parent class!
在父类中定义的功能!
While the child class can access the parent class methods, it can also provide a new implementation to the parent class methods, which is called method overriding.
虽然子类可以访问父类的方法,但是它也可以为父类的方法提供一个新的实现,称为方法重写 。
Python方法重载示例 (Python Method Overriding Example)
Let's take a very cool example which we also had in the inheritance tutorial. There is a parent class named Animal
:
让我们举一个非常酷的示例,该示例在继承教程中也有。 有一个名为Animal
的父类:
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
def breathe(self):
print("I breathe oxygen.")
# function feed
def feed(self):
print("I eat food.")
Let's create a child class Herbivorous
which will extend the class Animal
:
让我们创建一个子类Herbivorous
,它将扩展Animal
类:
class Herbivorous(Animal):
# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")
In the child class Herbivorous
we have overridden the method feed()
.
在子类Herbivorous
我们重写了feed()
方法。
So now when we create an object of the class Herbivorous
and call the method feed()
the overridden version will be executed.
因此,现在当我们创建类Herbivorous
的对象并调用feed()
方法时,将执行覆盖的版本。
herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()
I eat only plants. I am vegetarian. I breathe oxygen.
我只吃植物。 我是素食主义者。 我呼吸氧气。
Click on Run to see the code in action and feel free to make changesto it and run again.
单击“ 运行”以查看运行中的代码,并随时对其进行更改并再次运行。
翻译自: https://www.studytonight.com/python/method-overriding-in-python
python中类方法重写