python中的静态方法_Python中的静态方法和实例方法

formencode有一个classinstancemethod修饰符,它可以做您想要的。它要求该方法有2个参数(self和cls,其中一个可以根据调用上下文被传递None)

来自formencode/declarative.pyclass 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 (''

% (self.type.__name__, self.func.func_name))

else:

return (''

% (self.type.__name__, self.func.func_name, self.obj))

示例用法

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值