修饰器

作者: 小松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

相关文章

  • 类的修饰器

    是什么 修饰器是一个对类进行处理的函数。修饰器不仅可以修饰类,还可以修饰类的属性,但是修饰器不能用于函数。 怎么用...

  • 修饰器

    函数修饰符@,在函数定义时使用,放在函数前一行,对下一行的函数起修饰(修改)作用。被修饰函数会作为参数传递给修饰函...

  • 修饰器

    类的修饰 § ⇧ 许多面向对象的语言都有修饰器(Decorator)函数,用来修改类的行为。目前,有一个提案将这项...

  • 修饰器

    一、Babel 环境配置 安装依赖 配置 .babelrc 文件 运行文件 Babel 的官方网站提供一个在线转码...

  • 修饰器

    内置修饰器: staticmethod、classmethod和property 作用:把类中定义的实例方法变成静...

  • python修饰器的特殊用法

    最基本的修饰器包括了无参数的修饰器和带参数的修饰器,这两种修饰器都是针对函数的,讲解的博客已经很多了,就不再赘述了...

  • es6 修饰器

    写在前面,因为function存在变量提升,所以修饰器是只能修饰类,而不能修饰函数 修饰器是一个函数,用来修改类的...

  • es6学习笔记整理(十六)Decorators

    Decorator修饰器 修饰器是一个函数用来修改类的行为: 1、修饰器是一个函数 2、修改行为 3、修改类的行为...

  • ES6-修饰器

    首先放一段示例代码 代码中@testable即为一个修饰器。可以看到,修饰器本质上是一个函数。将类作为修饰器函数的...

  • ES6_修饰器

    修饰器@ 只能用于类 和 类的方法 类的修饰器 修饰器对类的行为的改变,是代码编译时发生的,而不是在运行时 方法的...

网友评论

      本文标题:修饰器

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