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

时间:2015-01-20 19:39:23

标签: python abc abstract-base-class

据我所知,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 个答案:

答案 0 :(得分:4)

你压倒__new__;正是这种方法(在object.__new__上)阻止了实例化。

您不是在此处创建不可变类型,也不是在更改新对象创建,因此请改用__init__

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

在任何情况下你都使用__new__错误;传入的第一个参数是,而不是实例,因为此时没有创建实例。通过覆盖__new__而不是调用原始文件,你a)不创建实例,b)不会触发阻止首先创建实例的代码。

使用__init__代替__new__实例化会按预期引发异常:

>>> 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