美文网首页
python常用的装饰器

python常用的装饰器

作者: 高稚商de菌 | 来源:发表于2018-08-18 15:29 被阅读0次

Python中有很多装饰器(decorator),可以减少冗余代码。Decorator本质上也是函数,只是它的参数也是函数。这里记录一下常用的decorator,方便以后查找。

  • staticmethod
    用来修饰类中的方法,使得该方法可以直接用类名访问,如cls.foo()。
  • classmethod
    和staticmehod类似,区别在于staticmethod,classmethod会将class传入被修饰的方法中。
class A(object):
    a = 1
    def __init__(self):
        self.a = 2

    @staticmethod
    def foo1():
        print A.a

    @classmethod
    def foo2(cls):
        print "class a is", cls.a
        print "instance a is", cls().a


A.foo1()
A.foo2()
  • property
    可以将属性的访问和赋值用函数来实现,从而可以在函数里添加参数检查等一些功能,同时外部使用时访问和赋值的方式并不发生变化。注意访问和赋值的方法名是一样的。
class A(object):
    def __init__(self):
        self.__count = 0

    @property
    def count(self):
        return self.__count

    @count.setter
    def count(self, value):
        if not isinstance(value, int):
            raise ValueError('count must be an integer!')
        self.__count = value


a = A()
print a.count
a.count = 1
print a.count
a.count = "a" # raise ValueError
  • functools.wraps
    用在装饰器的代码里。可以把原始函数的__name__等属性复制到wrapper()函数中,这样就可以获取到真实函数的__name__属性,而不是wrapper。
import functools

def log(text):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            print '%s %s():' % (text, func.__name__)
            return func(*args, **kw)
        return wrapper
    return decorator

待后续补充。。。

相关文章

网友评论

      本文标题:python常用的装饰器

      本文链接:https://www.haomeiwen.com/subject/dcjfiftx.html