Python抽象基类:为什么abc不能阻止实例化?

8
据我所理解,Python模块abc应该可以防止实例化未实现基类所有@abstractmethod标记方法的类(前提是基类已设置__metaclass__ = ABCMeta)。
但是,对于以下代码似乎不起作用:
抽象基类:
""" Contains payment processors for executing payments """

from abc import ABCMeta, abstractmethod

class AbstractPaymentProcessor:
    """ Abstract class for executing faucet Payments
    Implement this at your own. Possible implementations include
    online wallets and RPC calls to running dogecoin wallets """

    __metaclass__ = ABCMeta

    @abstractmethod
    def execute_payment(self, destination_address, amount):
        """ Execute a payment to one receiving single address

        return the transaction id or None """
        pass

    @abstractmethod
    def execute_multi_payment(self, destination_addresses, amounts):
        """ Execute a payment to multiple receiving addresses

        return the transaction id or None """
        pass

    @abstractmethod
    def get_transaction_status(self):
        """ Get the status of the transaction

        Indicate if transaction is already confirmed. Return
         - True if confirmed
         - False if unconfirmed
         - None if transaction doesn't exist (or raise exception?)"""
        pass

    @abstractmethod
    def get_available_balance(self):
        """ Get the available balance
        i.e. how much "cash" is in the faucet """
        pass

子类缺少方法:
""" Contains a logging payment processor """

import logging
import random

from AbstractPaymentProcessor import AbstractPaymentProcessor

class DummyLoggingPaymentProcessor (AbstractPaymentProcessor):
    """ Payment processor that does nothing, just logs """

    def __new__(self):
        self._logger = logging.getLogger(__name__)
        self._logger.setLevel(logging.INFO)

    def execute_payment(self, destination_address, amount):
        """ Execute a payment to one receiving single address

        return the transaction id or None """
        raise NotImplementedError("Not implemented yet")

    def execute_multi_payment(self, destination_addresses, amounts):
        """ Execute a payment to multiple receiving addresses

        return the transaction id or None """
        raise NotImplementedError("Not implemented yet")

    def get_transaction_status(self):
        """ Get the status of the transaction

        Indicate if transaction is already confirmed. Return
         - True if confirmed
         - False if unconfirmed
         - None if transaction doesn't exist """
        raise NotImplementedError("Not implemented yet")


if __name__ == '__main__':
    # can instanciate, although get_available_balance is not defined. Why? abc should prevent this!?
    c = DummyLoggingPaymentProcessor()
    c.get_available_balance()

这个子类可以在(相当粗糙的)测试代码中实例化,为什么?

我正在使用Python 2.7。

1个回答

6

你正在覆盖__new__方法;object.__new__上的这个方法可以防止实例化。

你没有创建一个不可变类型,也没有改变新对象的创建方式,因此请使用__init__代替:

def __init__(self):
    self._logger = logging.getLogger(__name__)
    self._logger.setLevel(logging.INFO)

无论如何,您都错误地使用了__new__;传递的第一个参数是class,而不是实例,因为此时没有创建任何实例。通过覆盖__new__并不调用原始函数,a)您没有创建实例,b)也未触发在第一次创建实例时防止其创建的代码。
相应的,当使用__init__进行实例化时,会像预期的那样引发异常:
>>> class DummyLoggingPaymentProcessor (AbstractPaymentProcessor):
...     """ Payment processor that does nothing, just logs """
...     def __init__(self):
...         self._logger = logging.getLogger(__name__)
...         self._logger.setLevel(logging.INFO)
...     def execute_payment(self, destination_address, amount):
...         """ Execute a payment to one receiving single address
... 
...         return the transaction id or None """
...         raise NotImplementedError("Not implemented yet")
...     def execute_multi_payment(self, destination_addresses, amounts):
...         """ Execute a payment to multiple receiving addresses
... 
...         return the transaction id or None """
...         raise NotImplementedError("Not implemented yet")
...     def get_transaction_status(self):
...         """ Get the status of the transaction
... 
...         Indicate if transaction is already confirmed. Return
...          - True if confirmed
...          - False if unconfirmed
...          - None if transaction doesn't exist """
...         raise NotImplementedError("Not implemented yet")
... 
>>> c = DummyLoggingPaymentProcessor()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class DummyLoggingPaymentProcessor with abstract methods get_available_balance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接