修饰器

内置修饰器:

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,860评论 2 9
  • 要点: 函数式编程:注意不是“函数编程”,多了一个“式” 模块:如何使用模块 面向对象编程:面向对象的概念、属性、...
    victorsungo阅读 1,587评论 0 6
  • 前言 对python的修饰器的理解一直停留在"使用修饰器把函数注册为事件的处理程序"的层次,也是一知半解;这样拖着...
    MrYun阅读 24,526评论 3 35
  • iOS获取设备唯一标识的各种方法?IDFA、IDFV、UDID分别是什么含义? 一、UDID (Unique De...
    金克拉拉拉拉阅读 708评论 0 0