Jak*_*ake 5 python static-methods descriptor instance-methods
我希望能够这样做:
class A(object):
@staticandinstancemethod
def B(self=None, x, y):
print self is None and "static" or "instance"
A.B(1,2)
A().B(1,2)
Run Code Online (Sandbox Code Playgroud)
这似乎是一个应该有一个简单解决方案的问题,但我无法想到或找到一个.
有可能,但请不要.我忍不住实现了它:
class staticandinstancemethod(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, klass=None):
def newfunc(*args, **kw):
return self.f(obj, *args, **kw)
return newfunc
Run Code Online (Sandbox Code Playgroud)
......及其用途:
>>> class A(object):
... @staticandinstancemethod
... def B(self, x, y):
... print self is None and "static" or "instance"
>>> A.B(1,2)
static
>>> A().B(1,2)
instance
Run Code Online (Sandbox Code Playgroud)
邪恶!
| 归档时间: |
|
| 查看次数: |
601 次 |
| 最近记录: |