相关疑难解决方法(0)

检查函数是否使用@classmethod

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在这个例子中所谓的内容

python decorator class-method python-decorators

12
推荐指数
3
解决办法
5669
查看次数

Python通过装饰类动态地将装饰器添加到类的方法中

说我上课了:

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)

python aop decorator

9
推荐指数
1
解决办法
7700
查看次数

标签 统计

decorator ×2

python ×2

aop ×1

class-method ×1

python-decorators ×1