如何在 Python 中实现虚拟方法? [英] How to implement virtual methods in Python?
问题描述
我知道 PHP 或 Java 中的虚方法.
I know virtual methods from PHP or Java.
如何在 Python 中实现它们?
How can they be implemented in Python?
或者我必须在抽象类中定义一个空方法并覆盖它吗?
Or have I to define an empty method in an abstract class and override it?
推荐答案
当然,您甚至不必在基类中定义方法.在 Python 中方法比虚拟更好 - 它们是完全动态的,因为 Python 中的输入是鸭子输入.
Sure, and you don't even have to define a method in the base class. In Python methods are better than virtual - they're completely dynamic, as the typing in Python is duck typing.
class Dog:
def say(self):
print "hau"
class Cat:
def say(self):
print "meow"
pet = Dog()
pet.say() # prints "hau"
another_pet = Cat()
another_pet.say() # prints "meow"
my_pets = [pet, another_pet]
for a_pet in my_pets:
a_pet.say()
Python 中的
Cat
和 Dog
甚至不必从公共基类派生来允许这种行为 - 您可以免费获得它.也就是说,一些程序员更喜欢以更严格的方式定义他们的类层次结构,以更好地记录它并强加一些类型的严格性.这也是可能的 - 例如参见 abc
标准模块一>.
Cat
and Dog
in Python don't even have to derive from a common base class to allow this behavior - you gain it for free. That said, some programmers prefer to define their class hierarchies in a more rigid way to document it better and impose some strictness of typing. This is also possible - see for example the abc
standard module.
这篇关于如何在 Python 中实现虚拟方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!