Sła*_*art 9 python methods decorator class-method python-decorators
有时我需要用静态方法编写类,但有可能初始化它并保持状态(对象)
......喜欢:
class A:
@classmethod
def method(cls_or_self):
# get reference to object when A().method() or to class when A.method()
code
Run Code Online (Sandbox Code Playgroud)
我现在拥有的是:
class A:
def method(self = None, *params): code
# or
def method2(self = None, **params): code
# but what I need is rather normal parameters, not optional and named args:
def method3(self_or_cls, a, b=1, c=2, *p, **kw): code
Run Code Online (Sandbox Code Playgroud)
请不要写关于staticmethod和classmethod之间的区别.我感兴趣的是,如果存在这样的装饰器(在或多或少的标准库中),而且如果上面适合于PEP.
Mar*_*ers 21
函数和classmethod
对象充当描述符 ; 两者都返回一个包装器,当被调用时将依次使用额外的参数调用底层函数.函数和classmethod
对象的行为方式之间的唯一区别在于额外的参数是什么.
要创建两种方法的混合,请构建自己的描述符装饰器:
from functools import wraps
class hybridmethod(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, cls):
context = obj if obj is not None else cls
@wraps(self.func)
def hybrid(*args, **kw):
return self.func(context, *args, **kw)
# optional, mimic methods some more
hybrid.__func__ = hybrid.im_func = self.func
hybrid.__self__ = hybrid.im_self = context
return hybrid
Run Code Online (Sandbox Code Playgroud)
在这里,我们返回一个包装器,它将使用类或实例作为第一个参数,具体取决于__get__
调用描述符方法时可用的内容.
演示:
>>> class Foo(object):
... @hybridmethod
... def bar(cls_or_self):
... print 'Called with cls_or_self={!r}'.format(cls_or_self)
...
>>> Foo.bar()
Called with cls_or_self=<class '__main__.Foo'>
>>> Foo().bar()
Called with cls_or_self=<__main__.Foo object at 0x1043a4390>
Run Code Online (Sandbox Code Playgroud)