python内置装饰器

1、@propery

将方法变为一个属性使用,访问时直接通过方法名来访问方法,不需要在方法名后添加"()"

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     @property
...     def myName(self):
...             print(self.name)
...     def myAddress(self):
...             print(self.address)
>>> myInfo=info('魏无羡','夷陵')
>>> myInfo.myName
魏无羡
>>> myInfo.myAddress
<bound method info.myAddress of <__main__.info object at 0x0000014C40456220>>
>>> myInfo.myAddress()
夷陵
>>>

2、@xx.setter

使用setter装饰器可以给myName添加setter方法。虽然加了property,函数好像是成为了类的属性,实际上类属性的很多特性是没有的,加上setter可以修改属性值。
没修改之前如果直接修改方法,结果如下:

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     @property
...     def myName(self):
...             print(self.name)
...     def myAddress(self):
...             print(self.address)
>>> myInfo=info('魏无羡','夷陵')
>>> myInfo.myName="蓝湛"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

可以看出直接修改被装饰器为属性的方法出错,下述加入setter后可以修改,如下:

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     @property
...     def myName(self):
...             print(self.name)
...     def myAddress(self):
...             print(self.address)
...     @myName.setter
...     def myName(self,value):
...             self.name=value
...             print(self.name)
...     AllName='cql'
...
>>>
>>> myInfo=info('魏无羡','夷陵')
>>> myInfo.myName
魏无羡
>>> myInfo.myAddress
<bound method info.myAddress of <__main__.info object at 0x0000014C403D0880>>
>>> myInfo.myAddress()
夷陵
>>> myInfo.AllName
'cql'
>>> myInfo.AllName="123"
>>> myInfo.AllName
'123'
>>> myInfo.myName="蓝湛"
蓝湛
>>> myInfo.myName
蓝湛
>>>

3、@xx.deleter

删除指定属性,同setter一样都是针对property装饰器的方法设置。
如2中设置直接进行删除出现如下情况:

>>> myInfo.AllName="123"
>>> myInfo.AllName
'123'
>>> del myInfo.AllName
>>> myInfo.AllName
'cql'
>>> del myInfo.myName
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't delete attribute
>>> class info:

修改后查看:

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     @property
...     def myName(self):
...             print(self.name)
...     def myAddress(self):
...             print(self.address)
...     @myName.setter
...     def myName(self,value):
...             self.name=value
...             print(self.name)
...     AllName='cql'
...     @myName.deleter
...     def myName(self):
...             self.name=("这其实调用了一个方法")
...             print(self.name)

运行结果:

>>> myInfo=info("wwx",'yl')
>>> myInfo.myName
wwx
>>> myInfo.myName='lz'
lz
>>> myInfo.myName
lz
>>> del myInfo.myName
这其实调用了一个方法
>>> myInfo.myName
这其实调用了一个方法
>>> myInfo.myName='lz'
lz
>>> myInfo.myName
lz
>>>


查看类的属性和使用装饰器为属性自身的属性如下:

>>> dir (myInfo.AllName)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
  '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__',
   '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
    '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', 
    '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
    '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
     'capitalize', 'casefold', 'center', 'count', 'encode',
      'endswith', 'expandtabs', 'find', 'format', 'format_map',
       'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
        'isdigit', 'isidentifier', 'islower', 'isnumeric', 
        'isprintable', 'isspace', 'istitle', 'isupper',
         'join', 'ljust', 'lower', 'lstrip', 'maketrans',
          'partition', 'replace', 'rfind', 'rindex', 'rjust',
           'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
            'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(myInfo.myName)
wqa
['__bool__', '__class__', '__delattr__', '__dir__', '__doc__',
 '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__gt__', '__hash__', '__init__', '__init_subclass__',
  '__le__', '__lt__', '__ne__', '__new__', '__reduce__',
   '__reduce_ex__', '__repr__', '__setattr__', 
   '__sizeof__', '__str__', '__subclasshook__']
>>>

4、@classmethod

带该修饰的类,cls作为第一个参数,隐式的将类作为对象,传输给方法,调用时无须对类实例话。但是普通的方法调用时必须加上类。

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     def myAddress(self):
...             print(self.address)
...     @classmethod
...     def myName(cls,name,address):
...             print(name+":"+address)
...     def myName_0(self):
...             print(self.name)
...
>>> myInfo=info("你好啊","吃了吗")
>>> myInfo.myName
<bound method info.myName of <class '__main__.info'>>
>>> myInfo.myName()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myName() missing 2 required positional arguments: 'name' and 'address'
>>> myInfo.myName_0()
你好啊
>>> info.myName('w','h')
w:h
>>> info.myName_0()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myName_0() missing 1 required positional argument: 'self'
>>>

第一个参数cls代表的是这个类,可以cls.x调用类的属性和方法:

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     def myAddress(self):
...             print(self.address)
...     @classmethod
...     def myName(cls,name,address):
...             print(name+":"+address)
...     def myName_0(self):
...             print(self.name)
...     value='class-info'
...     @classmethod
...     def myName2(cls,name,address):
...             print(cls.value+":::"+name+"::"+address)
...
>>> myInfo=info("你好啊","吃了吗")
>>> myInfo.myName
<bound method info.myName of <class '__main__.info'>>
>>> myInfo.myName_0()
你好啊
>>> info.myName('w','h')
w:h
>>> myInfo.myName2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myName2() missing 2 required positional arguments: 'name' and 'address'
>>> myInfo.myName2("ww",)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myName2() missing 1 required positional argument: 'address'
>>> myInfo.myName2("ww","hh")
class-info:::ww::hh
>>>

5、@staticmethod

和calssmethod用法相同,但是不需要cls,也就是该方法完全不需要调用类的属性和方法,也不需要实例话类。

>>> class info:
...     def __init__(self,name,address):
...             self.name=name
...             self.address=address
...     def myAddress(self):
...             print(self.address)
...     @classmethod
...     def myName(cls,name,address):
...             print(name+":"+address)
...     def myName_0(self):
...             print(self.name)
...     value='class-info'
...     @classmethod
...     def myName2(cls,name,address):
...             print(cls.value+":::"+name+"::"+address)
...     @staticmethod
...     def myName3(name,address):
...             print(name+" "+address)
...
>>> myInfo=info()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() missing 2 required positional arguments: 'name' and 'address'
>>> myInfo=info("wxe",'sgl')
>>> myInfo.myName
<bound method info.myName of <class '__main__.info'>>
>>> myInfo.myName_0()
wxe
>>> info.myName("w",'w')
w:w
>>> info.myName3("ss","swer")
ss swer
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值