Python classmethod outside the class

强颜欢笑 提交于 2019-12-11 14:37:17

问题


I have to use some Python library which contains file with various utilities: classes and methods. One of these methods is defined in the following way (I cannot put whole code):

@classmethod
def do_something(cls, args=None, **kwargs):

but this declaration is outside any class. How can I get access to this method? Calling by do_something(myClass) gives an error: TypeError: 'classmethod' object is not callable. What is the purpose of creating classmethods outside classes?


回答1:


The decorator produces a classmethod object. Such objects are descriptors (just like staticmethod, property and function objects).

Perhaps the code is re-using that object as such a descriptor. You can add it to a class at a later time:

ClassObject.attribute_name = do_something

or you can explicitly call the descriptor.__get__ method.

By storing it as a global it is easier to retrieve; if you put it on a class you'd have to reach into the class __dict__ attribute to retrieve the classmethod descriptor without invoking it:

ClassObject.__dict__['do_something']

as straight attribute access would cause Python to call the descriptor.__get_ method for you, returning a bound method:

>>> class Foo(object):
...     @classmethod
...     def bar(cls):
...         print 'called bar on {}'.format(cls.__name__)
... 
>>> Foo.bar
<bound method type.bar of <class '__main__.Foo'>>
>>> Foo.bar()
called bar on Foo
>>> Foo.__dict__['bar']
<classmethod object at 0x1076b20c0>
>>> Foo.__dict__['bar'].__get__(None, Foo)
<bound method type.bar of <class '__main__.Foo'>>
>>> Foo.__dict__['bar'].__get__(None, Foo)()
called bar on Foo


来源:https://stackoverflow.com/questions/32284275/python-classmethod-outside-the-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!