修饰器

作者: 小松qxs | 来源:发表于2019-01-22 11:36 被阅读0次

    内置修饰器:

    staticmethod、classmethod和property

    作用:把类中定义的实例方法变成静态方法、类方法和类属性。

    1、staticmethod
    staticmethod把类中的函数定义成静态方法

    class Foo:
        @staticmethod #装饰器
        def spam(x,y,z):
            print(x,y,z)
    
    print(type(Foo.spam)) #类型本质就是函数
    Foo.spam(1,2,3) #调用函数应该有几个参数就传几个参数
    f1=Foo()
    f1.spam(3,3,3) #实例也可以使用,但通常静态方法都是给类用的,实例在使用时丧失了自动传值的机制
    '''
    <class 'function'>
    1 2 3
    3 3 3
    '''
    

    2、classmethod
    对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

    class A(object):
        bar = 1
        def func1(self):  
            print ('foo') 
        @classmethod
        def func2(cls):
            print ('func2')
            print (cls.bar)
            cls().func1()   # 调用 foo 方法
     
    A.func2() 
    
    '''
    func2
    1
    foo
    '''
    
    class A:
        x=1
        @classmethod
        def test(cls):
            print(cls, cls.x)
    
    class B(A):
        x=2
    B.test()
    
    '''
    输出结果:
    <class '__main__.B'> 2
    '''
    

    3、property
    优势:遵循了统一访问的原则
    类绑定属性时,属性暴露,写起来简单,但无法检查参数,导致成绩随便改:

    s = Student()
    s.score = 9999
    

    为了限制score的范围,通过set_score()方法设置成绩,通过get_score()获取成绩,在set_score()方法里可以检查参数,但是调用方法不如直接用属性简单。:

    class Student(object):
        def get_score(self):
            return self._score
    
        def set_score(self, value):
            if not isinstance(value, int):
                raise ValueError('score must be an integer!')
            if value < 0 or value > 100:
                raise ValueError('score must between 0 ~ 100!')
            self._score = value
    

    对任意的Student实例操作,score可限制范围:

    >>> s = Student()
    >>> s.set_score(60) # ok!
    >>> s.get_score()
    60
    >>> s.set_score(9999)
    Traceback (most recent call last):
      ...
    ValueError: score must between 0 ~ 100!
    

    既能检查参数,又可以用类似属性的方式:

    decorator可以给函数动态加功能,对于类方法,Python内置的@property装饰器就是负责把一个方法变成属性调用:

    class Student(object):
        @property
        def score(self):
            return self._score
    
        @score.setter
        def score(self, value):
            if not isinstance(value, int):
                raise ValueError('score must be an integer!')
            if value < 0 or value > 100:
                raise ValueError('score must between 0 ~ 100!')
            self._score = value
    

    把一个getter方法变成属性,只需要加上@property,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,可控的属性操作如下:

    >>> s = Student()
    >>> s.score = 60 # OK,实际转化为s.set_score(60)
    >>> s.score # OK,实际转化为s.get_score()
    60
    >>> s.score = 9999
    Traceback (most recent call last):
      ...
    ValueError: score must between 0 ~ 100!
    

    @property,对实例属性操作时属性不是直接暴露,而是通过getter和setter方法来实现。

    只定义getter方法,不定义setter方法就是一个只读属性:

    class Student(object):
        @property
        def birth(self):
            return self._birth
    
        @birth.setter
        def birth(self, value):
            self._birth = value
    
        @property
        def age(self):
            return 2014 - self._birth
    

    birth是可读写属性,age是只读属性,因为age可以根据birth和当前时间计算出来。

    https://www.jianshu.com/p/ab702e4d4ba7
    https://blog.csdn.net/xx5595480/article/details/72510854

    相关文章

      网友评论

          本文标题:修饰器

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