Python装饰器与面向切面编程

本文详细介绍了Python中类方法、实例方法及静态方法的使用与区别,并深入探讨了@property装饰器的功能及其应用场景。
Python装饰器与面向切面编程
 
 
 
 
 
 
python 中类方法、类实例方法和静态方法的使用与区别:
 
使用方法:

  1. class A(object):
  2.     def foo(self,x):
  3.         #类实例方法
  4.         print "executing foo(%s,%s)"%(self,x)

  5.     @classmethod
  6.     def class_foo(cls,x):
  7.         #类方法
  8.         print "executing class_foo(%s,%s)"%(cls,x)

  9.     @staticmethod
  10.     def static_foo(x):
  11.         #静态方法
  12.         print "executing static_foo(%s)"%x

调用方法:

  1. = A()
  2. a.foo(1)

  3. a.class_foo(1)
  4. A.class_foo(1)

  5. a.static_foo(1)
  6. A.static_foo(1)

运行方法:

  1. executing foo(<__main__.A object at 0xb77d67ec>,1)
  2. executing class_foo(<class '__main__.A'>,1)
  3. executing class_foo(<class '__main__.A'>,1)
  4. executing static_foo(1)
  5. executing static_foo(1)

 

区别:

  • 类方法和静态方法都可以被类和类实例调用,类实例方法仅可以被类实例调用
  • 类方法的隐含调用参数是类,而类实例方法的隐含调用参数是类的实例,静态方法没有隐含调用参数



python @property

@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/getter也是需要的,我们视具体情况吧

请注意以下代码场景: (Python2.6代码)


 

  1. class Parrot(object): 
  2.     def __init__(self): 
  3.         self._voltage = 100000 
  4.   
  5.     @property 
  6.     def voltage(self): 
  7.         """Get the current voltage.""" 
  8.         return self._voltage 
  9.   
  10. if __name__ == "__main__": 
  11.     # instance 
  12.     p = Parrot() 
  13.     # similarly invoke "getter" via @property 
  14.     print p.voltage 
  15.     # update, similarly invoke "setter" 
  16.     p.voltage = 12

代码片段2:

  1. class Parrot: 
  2.     def __init__(self): 
  3.         self._voltage = 100000 
  4.   
  5.     @property 
  6.     def voltage(self): 
  7.         """Get the current voltage.""" 
  8.         return self._voltage 
  9.   
  10. if __name__ == "__main__": 
  11.     # instance 
  12.     p = Parrot() 
  13.     # similarly invoke "getter" via @property 
  14.     print p.voltage 
  15.     # update, similarly invoke "setter" 
  16.     p.voltage = 12

代码1、2的区别在于 
class Parrot(object): 

在python2.6下,分别运行测试 
片段1:将会提示一个预期的错误信息 AttributeError: can't set attribute 
片段2:正确运行 

参考python2.6文档,@property将提供一个ready-only property,以上代码没有提供对应的@voltage.setter,按理说片段2代码将提示运行错误,在python2.6文档中,我们可以找到以下信息: 

BIF: 
property([fget[, fset[, fdel[, doc]]]]) 
Return a property attribute for new-style classes (classes that derive from object). 
原来在python2.6下,内置类型 object 并不是默认的基类,如果在定义类时,没有明确说明的话(代码片段2),我们定义的Parrot(代码片段2)将不会继承object 

而object类正好提供了我们需要的@property功能,在文档中我们可以查到如下信息: 

new-style class 
Any class which inherits from object. This includes all built-in types like list and dict. Only new-style classes can use Python's newer, versatile features like __slots__, descriptorsproperties, and __getattribute__(). 

  1. class A: pass 
  2. >>type(A) 
  3. <type 'classobj'> 

  4. class A(object): pass 
  5. >>type(A) 
  6. <type 'type'>


从返回的<type 'classobj'>,<type 'type'>可以看出<type 'type'>是我们需要的object类型(python 3.0 将object类作为默认基类,所以都将返回<type 'type'>) 


为了考虑代码的python 版本过渡期的兼容性问题,我觉得应该定义class文件的时候,都应该显式定义object,做为一个好习惯

  1. class Parrot(object): 
  2.     def __init__(self): 
  3.         self._voltage = 100000 

  4.     @property 
  5.     def voltage(self): 
  6.         """Get the current voltage.""" 
  7.         return self._voltage 

  8.     @voltage.setter 
  9.     def voltage(self, new_value): 
  10.         self._voltage = new_value 
  11.   
  12. if __name__ == "__main__": 
  13.     # instance 
  14.     p = Parrot() 
  15.     # similarly invoke "getter" via @property 
  16.     print p.voltage 
  17.     # update, similarly invoke "setter" 
  18.     p.voltage = 12

 

另外,@property是在2.6、3.0新增的,2.5没有该功能。

1
2
3
4
def foo():
    print 'in foo()'
  
foo()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值