简体   繁体   English

如何在zope.interface中声明@staticmethod

[英]How to declare @staticmethod in zope.interface

I try to create interface with @staticmethod and @classmethod. 我尝试使用@staticmethod和@classmethod创建接口。 Declaring class method is simple. 声明类方法很简单。 But I can't find the correct way to declare static method. 但是我找不到声明静态方法的正确方法。

Consider class interface and its implementation: 考虑类接口及其实现:

#!/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'))

Output: 输出:

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.

How should I correctly declare static method in this interface? 我应该如何在此接口中正确声明静态方法?

Obviously the verifyClass does not understand either classmethod or staticmethod properly. 显然, verifyClass不能正确地理解classmethodstaticmethod The problem is that in Python 3, if you do getattr(MyObject, 'load_index_list') in Python 3, you get a bare function, and verifyClass thinks it is yet another unbound method , and then expects that the implicit self be the first argument. 问题在于,在Python 3中,如果在Python 3中执行getattr(MyObject, 'load_index_list') ,则会得到一个裸函数,并且verifyClass认为这是另一个未绑定的方法 ,然后期望隐式self是第一个参数。

The easiest fix is to use a classmethod there instead of a staticmethod . 最简单的解决方法是在其中使用classmethod ,而不是staticmethod

I guess someone could also do a bug report. 我猜有人也可以报告错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM