我尝试使用@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.
我应该如何在此界面中正确声明静态方法?
答案 0 :(得分:0)
显然,verifyClass
无法正确理解classmethod
或staticmethod
。问题是在Python 3中,如果在Python 3中执行getattr(MyObject, 'load_index_list')
,则会得到一个简单的函数,而verifyClass
认为它是另一个未绑定的方法,然后期望隐式self
是第一个参数。
最简单的解决方法是使用classmethod
代替staticmethod
。
我想有人也可以做错误报告。