Python的super()、抽象基类和NotImplementedE

2024-04-27 04:47:47 发布

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

Abstract base classes can still be handy in Python.在写一个抽象基类时,我希望每个子类都有一个spam()方法,我希望这样写:

class Abstract(object):
    def spam(self):
        raise NotImplementedError

挑战还在于希望使用super(),并通过将其包含在整个子类链中来正确地执行它。在这种情况下,我似乎必须像下面这样包装每个super调用:

class Useful(Abstract):
    def spam(self):
        try:
            super(Useful, self).spam()
        except NotImplementedError, e:
            pass
        print("It's okay.")

对于一个简单的子类来说这是可以的,但是当编写一个有很多方法的类时,try-except的事情变得有点麻烦,也有点难看。有没有更优雅的方法从抽象基类中进行子类化?我只是做错了吗?


Tags: 方法selfabstractbasedefspam基类子类
3条回答

不要写所有的代码。对抽象类的简单检查可以节省编写所有代码的时间。

如果方法是抽象的,则具体子类不调用super。

如果方法是具体的,则具体子类将调用super。

在python 2.6+中,您可以使用abc module轻松地完成此操作:

import abc
class B(object):
    __metaclass__ = abc.ABCMeta
    @abc.abstractmethod
    def foo(self):
        print 'In B'

class C(B):
    def foo(self):
        super(C, self).foo()
        print 'In C'

C().foo()

输出将是

In B
In C

理解这一点的关键是实现协作继承。类如何协作取决于程序员。super()不是魔法,也不知道你到底想要什么!在不需要合作继承的平面层次结构中使用super没有多大意义,因此在这种情况下,S.Lott的建议是正确的。有用的子类可能要也可能不想使用super(),这取决于它们的目标:)

例如:Abstract是A.A<;-B,但是您希望支持插入C,就像A<;-C<;-B一样

class A(object):                                                                                         
    """I am an abstract abstraction :)"""
    def foo(self):
        raise NotImplementedError('I need to be implemented!')

class B(A):
    """I want to implement A"""
    def foo(self):
        print('B: foo')
        # MRO Stops here, unless super is not A
        position = self.__class__.__mro__.index
        if not position(B) + 1 == position(A):
            super().foo()

b = B()     
b.foo()

class C(A):
    """I want to modify B and all its siblings (see below)"""
    def foo(self):
        print('C: foo')
        # MRO Stops here, unless super is not A
        position = self.__class__.__mro__.index
        if not position(C) + 1 == position(A):
            super().foo()

print('')   
print('B: Old __base__ and __mro__:\n')
print('Base:', B.__bases__)
print('MRO:', B.__mro__)
print('')
# __mro__ change implementation
B.__bases__ = (C,)
print('B: New __base__ and __mro__:\n')
print('Base:', B.__bases__)
print('MRO:', B.__mro__)
print('')
b.foo()

以及输出:

B: foo

B: Old __base__ and __mro__:

Base: (<class '__main__.A'>,)
MRO: (<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)

B: New __base__ and __mro__:

Base: (<class '__main__.C'>,)
MRO: (<class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

B: foo
C: foo

相关问题 更多 >