简体   繁体   English

类外的Python类方法

[英]Python classmethod outside the class

I have to use some Python library which contains file with various utilities: classes and methods.我必须使用一些 Python 库,其中包含具有各种实用程序的文件:类和方法。 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 .通过do_something(myClass)调用会报错: TypeError: 'classmethod' object is not callable What is the purpose of creating classmethods outside classes?在类外创建类方法的目的是什么?

The decorator produces a classmethod object.装饰器产生一个classmethod对象。 Such objects are descriptors (just like staticmethod , property and function objects).这些对象是描述符(就像staticmethodproperty和函数对象)。

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 thedescriptor.__get__ method .或者您可以显式调用descriptor.__get__方法

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:如果你把它放在一个类上,你必须进入类__dict__属性来检索classmethod描述符而不调用它:

ClassObject.__dict__['do_something']

as straight attribute access would cause Python to call the descriptor.__get_ method for you, returning a bound method:因为直接访问属性会导致 Python 为您调用descriptor.__get_方法,返回一个绑定方法:

>>> 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

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

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