我可以将 Python 方法同时定义为静态和实例吗?就像是:
class C(object):
@staticmethod
def a(self, arg1):
if self:
blah
blah
这样我就可以同时调用它:
C.a(arg1)
C().a(arg1)
目的是能够运行两组逻辑。如果作为实例方法访问,它将使用实例变量并做一些事情。如果访问作为静态方法,则无需。
我可以将 Python 方法同时定义为静态和实例吗?就像是:
class C(object):
@staticmethod
def a(self, arg1):
if self:
blah
blah
这样我就可以同时调用它:
C.a(arg1)
C().a(arg1)
目的是能够运行两组逻辑。如果作为实例方法访问,它将使用实例变量并做一些事情。如果访问作为静态方法,则无需。
import functools
class static_or_instance(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, owner):
return functools.partial(self.func, instance)
class C(object):
@static_or_instance
def a(self, arg):
if self is None:
print "called without self:", arg
else:
print "called with self:", arg
C.a(42)
C().a(3)
formencode有一个classinstancemethod
装饰器,它可以做你想做的事。它要求该方法具有 2 个参数(self
并且cls
,其中一个可以None
根据调用上下文传递)
从formencode/declarative.py
class classinstancemethod(object):
"""
Acts like a class method when called from a class, like an
instance method when called by an instance. The method should
take two arguments, 'self' and 'cls'; one of these will be None
depending on how the method was called.
"""
def __init__(self, func):
self.func = func
def __get__(self, obj, type=None):
return _methodwrapper(self.func, obj=obj, type=type)
class _methodwrapper(object):
def __init__(self, func, obj, type):
self.func = func
self.obj = obj
self.type = type
def __call__(self, *args, **kw):
assert not kw.has_key('self') and not kw.has_key('cls'), (
"You cannot use 'self' or 'cls' arguments to a "
"classinstancemethod")
return self.func(*((self.obj, self.type) + args), **kw)
def __repr__(self):
if self.obj is None:
return ('<bound class method %s.%s>'
% (self.type.__name__, self.func.func_name))
else:
return ('<bound method %s.%s of %r>'
% (self.type.__name__, self.func.func_name, self.obj))
示例使用
class A(object):
data = 5
@classinstancemethod
def print_(self=None, cls=None):
ctx = self or cls
print ctx.data
>>> A.print_()
5
>>> a = A()
>>> a.data = 4
>>> a.print_()
4
不self
。如果你能做到,那么方法内部意味着什么?
如果您将self
参数删除到a()
. 当您使用C().a(arg1)
实例调用它时,将被忽略。
但是您希望此方法既可用作静态方法,又可用作接收实例的方法。你不能两全其美。