gpt4 book ai didi

python - 如何在 Python 中实现虚方法?

转载 作者:IT老高 更新时间:2023-10-28 21:39:01 25 4
gpt4 key购买 nike

我知道 PHP 或 Java 的虚拟方法。

如何在 Python 中实现它们?

或者我必须在抽象类中定义一个空方法并覆盖它吗?

最佳答案

当然,您甚至不必在基类中定义方法。在 Python 中方法比虚拟方法更好——它们是完全动态的,因为 Python 中的输入是 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 中的

CatDog 甚至不必从公共(public)基类派生来允许这种行为 - 您可以免费获得它。也就是说,一些程序员更喜欢以更严格的方式定义他们的类层次结构,以便更好地记录它并施加一些严格的输入。这也是可能的 - 例如见 abc standard module .

关于python - 如何在 Python 中实现虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4714136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com