Python纯虚拟函数是可能的还是值得的?

2024-03-29 04:48:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我可能来自不同的思维方式,主要是C++程序员。这个问题与Python中的OOP以及更具体的纯虚拟方法有关。所以我从this question改编的代码来看这个基本示例。

class Animal():
    def speak(self):
        print("...")

class Cat(Animal):
    def speak(self):
        print("meow")

class Dog(Animal):
    def speak(self):
        print("woof")

my_pets = [Dog(), Cat(), Dog()]

for _pet in my_pets:
     _pet.speak()

所以您可以看到它为不同的派生类调用speak函数。现在我的问题是鸭子打字很好,我想我已经掌握了。然而,在Python中追求更严格的OOP是错误的吗?所以我看了Abstract Base Classes,特别是abstractmethod。对我来说,所有这些似乎只是允许我用super调用基类方法。有没有任何方法/理由(在Python中)使speak()变得纯粹,以至于在不说话的情况下实现派生的动物会抛出错误?

我支持这样一种追求的理由是,当编写您希望人们进行子类化的模块和框架时,这将为他们自己记录他们需要实现该功能的事实。一个可能非常糟糕的想法是这样的,让基类“pure”函数抛出异常。问题是这个错误是在运行时发现的!

class VirtualException(BaseException):
    def __init__(self, _type, _func):
        BaseException(self)

class Animal():
    def speak(self):
        raise VirtualException()

class Cat(Animal):
    def speak(self):
        print("meow")

class Dog(Animal):
    def speak(self):
        print("woof")

class Wildebeest(Animal):
    def function2(self):
        print("What!")

my_pets = [Dog(), Cat(), Dog(), Wildebeest()]

for _pet in my_pets:
    _pet.speak()

Tags: 方法selfmydef错误oopclasscat
2条回答

抽象基类已经做了您想要的事情。abstractmethod与让您使用super调用方法无关;无论如何,您都可以这样做。相反,必须重写用abstractmethod修饰的任何方法,才能使子类可实例化:

Python3:

>>> class Foo(metaclass=abc.ABCMeta):
...     @abc.abstractmethod
...     def foo(self):
...         pass
...
>>> class Bar(Foo):
...     pass
...
>>> class Baz(Bar):
...     def foo(self):
...         return super(Baz, self).foo()
...
>>> Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Foo with abstract methods foo
>>> Bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Bar with abstract methods foo
>>> Baz()
<__main__.Baz object at 0x00000210D702E2B0>

Python2:

>>> class Foo(object):
...     __metaclass__ = abc.ABCMeta
...     @abc.abstractmethod
...     def foo(self): pass
...
>>> class Bar(Foo): pass
...
>>> class Baz(Bar):
...     def foo(self): return super(Baz, self).foo()
...
>>> Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Foo with abstract methods foo
>>> Bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Bar with abstract methods foo
>>> Baz()
<__main__.Baz object at 0x0000000001EC10B8>

Problem is that this error is found at runtime!

嗯,是Python。。。大多数错误都会在运行时出现。

据我所知,最常见的模式是在Python中,基本上就是您所描述的:让基类的speak方法抛出一个异常:

class Animal():
    def speak(self):
        raise NotImplementedError('You need to define a speak method!')

相关问题 更多 >