【问题标题】:How to use Abstract Base Classes in Python?如何在 Python 中使用抽象基类?
【发布时间】:2014-03-12 13:17:56
【问题描述】:

this tutorial 之后,我正在尝试在 Python 中使用抽象基类。于是我构建了两个文件:

basis.py

import abc

class PluginBase(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def load(self, input):
        return

implementation.py

import abc
from basis import PluginBase

class SubclassImplementation(PluginBase):

    def load(self, input):
        print input
        return input

if __name__ == '__main__':
    print 'Subclass:', issubclass(SubclassImplementation, PluginBase)
    print 'Instance:', isinstance(SubclassImplementation(), PluginBase)

运行python implementation.py 工作正常,但我现在想将implementation.py 用作其他模块。所以我进入命令行并执行:

>>> from implementation import SubclassImplementation as imp
>>> imp.load('lala')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method load() must be called with SubclassImplementation instance as first argument (got str instance instead)
>>>

我在这里做错了什么,我怎样才能做到这一点?欢迎所有提示!

【问题讨论】:

    标签: python abstract-class abc


    【解决方案1】:

    你确实需要创建一个实例

    from implementation import SubclassImplementation as imp
    
    imp().load('lala')
    

    这也不是一个特定的 ABC 问题;这适用于所有 Python 类和方法,除非您将 SubclassImplementation.load 设为 classmethod

    【讨论】:

    • 我也对 Daniel 说过,我最近一直在使用 php 静态函数(bLuh,我喜欢 Python!),我完全忘记了这一点。还是谢谢!
    【解决方案2】:

    这与 ABC 无关。

    您称为imp 的对象是一个类,即SubclassImplementation。您需要先实例化它,然后才能调用它的任何实例方法。或者,您可以将load 设为类方法。

    【讨论】:

    • 我多么愚蠢。最近我一直在 php 中使用静态函数,所以我已经习惯了直接从一个类中运行函数,以至于我忘记了实例。还是谢谢!
    猜你喜欢
    • 2016-10-22
    • 2018-11-06
    • 2014-02-17
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2019-05-02
    相关资源
    最近更新 更多