装饰器详细解读-python

Python的装饰器真是一个很好用的东西,可以很漂亮的简化程序,只需要在方法或者类加上@xxx 就可以获得该装饰器的功能,下面这两篇博客很好的解释了装饰器,非常详细:

https://www.cnblogs.com/cicaday/p/python-decorator.html

https://www.cnblogs.com/cicaday/p/python-decorator-more-usages.html

Property(属性函数)是一个很重要的概念在python中,那么具体是什么作用呢,结合程序来看更好理解。

   本篇会涉及到类的基本使用,property的使用,以及@property的使用。

    (1)首先是一个简单的demo:

class person():
    def __init__(self,sex,age):      # 两个属性 sex and age
        self._sex=sex               
        self._age=age
        
    def get_info(self):
        return self._sex,self._age
    
    def set_info(self,sex,age):
        if sex=='man' or sex=='women':
            self._sex=sex
        else:
            raise Exception("illegal sex input !")
        if age<100 and age>0:
            self._age=age+1
A=person('wwomen',18)
A._age
# output 18

 

    大家肯定回想为什么要用get_info和set_info这两种方法(方法:绑定到对象特性上面的函数,本质是函数)呢?为什么这么操作,而不是直接操作,比如像下面这样:


#通过get_info set_info 间接操作

A.set_info('man',18)

#直接操作 A._age=18 A._sex='man'

 

  我们也可以直接操作,也可以间接操作,但是在平时用到的时候,我们用的大都是间接操作(也就是封装的思想),我们会加入很多限制条件,或者对属性的运算在里面,所以直接操作很不方便。那有了这个思想之后呢,就可以看接下来的代码了。

 

class person():
    def __init__(self,age):
        self._age=age
        
    def get_info(self):
        return self._age
    
    def set_info(self,age):
        if age<100 and age>0:
            self._age=age+1           # 这里为了观察是否调用了该方法,特意把该值加一
    age_info=property(fget=get_info,fset=set_info)    # add property method

 

  那么我们加入了property,程序输出会有什么变化么,看一下程序的输出:

先定义一个实例(对象),然后我们调用了age_info,为什么加入property方法呢,一是可以让age_info这个方法可以和属性一样进行“ .”调用,二是可以看到当我们调用age_info的时候,自动调用了get_info方法,下面给age_info复制的时候自动调用了set_info方法。(装饰器返回的是函数(方法))

B=person(10)
B.age_info
# output  10
 
B.age_info=12
B.age_info
# output 13


B.age_info=12B.age_info# output 13

 

那么接下来@property装饰器就好理解了:还是直接上程序,看输出

class person():
    def __init__(self,age):
        self._age=age
        
    @property               # 将方法改成属性,可以直接由对象调用
    def age_info(self):
        return self._age
    
    @age_info.setter
    def age_info(self,age):
        if age<100 and age>0:
            self._age=age+1

 

 

 

C=person(10)

C.age_info

# output 10

C.age_info=22
C.age_info
# output 23

 

看到了吧,和之前一样的效果。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值