1

我尝试使用@staticmethod 和@classmethod 创建接口。声明类方法很简单。但我找不到声明静态方法的正确方法。

考虑类接口及其实现:

#!/usr/bin/python3
from zope.interface import Interface, implementer, verify


class ISerializable(Interface):

    def from_dump(slice_id, intex_list, input_stream):
        '''Loads from dump.'''

    def dump(out_stream):
        '''Writes dump.'''

    def load_index_list(input_stream):
        '''staticmethod'''


@implementer(ISerializable)
class MyObject(object):

    def dump(self, out_stream):
        pass

    @classmethod
    def from_dump(cls, slice_id, intex_list, input_stream):
        return cls()

    @staticmethod
    def load_index_list(stream):
        pass

verify.verifyClass(ISerializable, MyObject)
verify.verifyObject(ISerializable, MyObject())
verify.verifyObject(ISerializable, MyObject.from_dump(0, [], 'stream'))

输出:

Traceback (most recent call last):
  File "./test-interface.py", line 31, in <module>
    verify.verifyClass(ISerializable, MyObject)
  File "/usr/local/lib/python3.4/dist-packages/zope/interface/verify.py", line 102, in verifyClass
    return _verify(iface, candidate, tentative, vtype='c')
  File "/usr/local/lib/python3.4/dist-packages/zope/interface/verify.py", line 97, in _verify
    raise BrokenMethodImplementation(name, mess)
zope.interface.exceptions.BrokenMethodImplementation: The implementation of load_index_list violates its contract
        because implementation doesn't allow enough arguments.

我应该如何在这个接口中正确声明静态方法?

4

1 回答 1

0

显然,verifyClass不理解classmethod或不staticmethod正确。问题是在 Python 3 中,如果你getattr(MyObject, 'load_index_list')在 Python 3 中这样做,你会得到一个裸函数,并verifyClass认为它是另一个未绑定的方法,然后期望隐式self是第一个参数。

最简单的解决方法是使用 aclassmethod而不是 a staticmethod

我想有人也可以做一个错误报告。

于 2015-03-21T16:41:04.750 回答