TL; DR如何确定函数是使用定义@classmethod还是具有相同效果的函数?
我的问题
为了实现类装饰器,我想检查一个方法是否将类作为其第一个参数,例如,实现了via
@classmethod
def function(cls, ...):
Run Code Online (Sandbox Code Playgroud)
我发现了一个解决方案,以检查@staticmethod通过types模块(isinstance(foo, types.UnboundMethodType)是False,如果foo是静态的,见这里),但没有找到如何做到这一点的任何东西@classmethod
上下文
我想要做的是一些事情
def class_decorator(cls):
for member in cls.__dict__:
if (isclassmethod(getattr(cls, member))):
# do something with the method
setattr(cls, member, modified_method)
return cls
Run Code Online (Sandbox Code Playgroud)
我不知道如何实现我isclassmethod在这个例子中所谓的内容
说我上课了:
class x:
def first_x_method(self):
print 'doing first_x_method stuff...'
def second_x_method(self):
print 'doing second_x_method stuff...'
Run Code Online (Sandbox Code Playgroud)
和这个装饰
class logger:
@staticmethod
def log(func):
def wrapped(*args, **kwargs):
try:
print "Entering: [%s] with parameters %s" % (func.__name__, args)
try:
return func(*args, **kwargs)
except Exception, e:
print 'Exception in %s : %s' % (func.__name__, e)
finally:
print "Exiting: [%s]" % func.__name__
return wrapped
Run Code Online (Sandbox Code Playgroud)
我将如何编写另一个装饰器,otherdecorator以便:
@otherdecorator(logger.log)
class x:
def first_x_method(self):
print 'doing x_method stuff...'
def first_x_method(self):
print 'doing x_method stuff...'
Run Code Online (Sandbox Code Playgroud)
同样的
class x:
@logger.log …Run Code Online (Sandbox Code Playgroud)