python - 装饰类的特定方法

标签 python decorator static-methods

我读到了有关装饰器的内容,并且我正在尝试装饰类的所有方法而不使用静态方法。

现在我只使用我为非静态的特定函数编写的装饰器,所以我想知道是否有一种方法可以既装饰很多方法又避免静态方法

我用我的装饰器得到了什么:

TypeError: unbound method test() must be called with ClassTest instance as first argument (got nothing instead)

我的装饰器:

def decorator(func):
    def wrapper(self, *args, **kwargs):
        print "test"
        return func(self, *args, **kwargs)
    return wrapper

最佳答案

首先,装饰一个类非常简单:

def class_decorator(cls):
    # modify cls
    return cls

为了向方法添加/删除/修改功能,您可以使用方法(或变量)的修饰版本调用 setattr:

setattr(some_class, some_attribute, decorator(some_callable))

为了区分不同类型的方法,您可以使用几个属性 判断一个方法是否是实例/类/静态方法。

完整的工作示例:

def _is_instance_method(var):
    if not hasattr(var, '__call__'): # It's not a callable
        return False
    if not hasattr(var, 'im_self'): # It's a callable, but it's not a bound method
        return False
    if getattr(var, 'im_self') is not None: # At this point, if it's a class method,
                                            # it will be bound to the class, while
                                            # the instance method is still unbound
                                            # return False if it's bound (i.e. a class method)
        return False
    return True # All that remains is a callable, that's boundable, but not yet -- an instance method!

def func_decorator(func):
    def func_wrapper(self, *args, **kwargs):
        print "Inside %s!" % (func.__name__,)
        return func(self, *args, **kwargs)
    return func_wrapper

def class_decorator(cls):
    for attr in cls.__dict__:
        var = getattr(cls, attr)
        if _is_instance_method(var): # Determine whether the attribute is an instance method
            setattr(cls, attr, func_decorator(var)) # Replace the function with a decorated one
    return cls # Return the class with its new decorated instance methods

@class_decorator
class B(object):

    @staticmethod
    def static_method():
        return "static method"

    @classmethod
    def cls_method(cls):
       return "cls method"

    def instance_method(self):
       return "instance method"

print B.static_method() 
print B.cls_method()
b = B()
print b.instance_method()

关于python - 装饰类的特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35526210/

相关文章:

python - 如果我有 PYC 文件,是否需要安装 Python?

Python 3.4 - 将字符串输入格式化为标题格式

python 包装器函数在装饰器中接受参数

python - Bottle 导致 python 程序崩溃?使用线程、队列和 fork 的简单实现

python pandas dataframe if else 不遍历数据框

java - 带有装饰器模式的 MVC

typescript - 是否可以为方法装饰器选项提供类型安全

kotlin - kotlin中如何使用子类调用父静态方法?

java - 在使用它的方法之前初始化一个 util 类是否可以?

java - 为什么 eclipse 告诉我静态方法引用 ClassName::staticMethod 应该为 "accessed in a static way"?