1. 程式人生 > >Python class的屬性訪問控制和內建函數重寫實現高級功能以及@property

Python class的屬性訪問控制和內建函數重寫實現高級功能以及@property

back 實例 溫習 error: blog sta rac bubuko 訪問

一、類屬性的訪問控制

Python Class確實是博大精深,我們還是來溫習一下屬性的訪問控制作為開(fu)場(xi)。

首先_varname是可以訪問的,__varname是不能直接訪問(原理是__varname變成了_classname__varname)

 1 >>> class A:
 2 ...     _aa = 1
 3 ...     __bb = 2
 4 ...
 5 >>>
 6 >>>
 7 >>> c = A()
 8 >>> c._aa
 9 1
10 >>> c.__bb
11 Traceback (most recent call last): 12 File "<stdin>", line 1, in <module> 13 AttributeError: A instance has no attribute __bb 14 >>> c._A__bb 15 2 16 >>>

二、內建函數:

不想啰嗦直接上代碼,註釋來講解:

 1 class Person(object):
 2     def __init__(self,name):
 3             self.name = name
 4     def __str__(self):
 5             return  "<class:Person Name:%s>"%self.name
 6     def __repr__(self):
 7             return  "<Name:%s>"%self.name
 8 
 9 tom = Person("
Tom") 10 print repr(tom) 11 print tom

技術分享圖片

 1 class Person(object):
 2     def __init__(self,name,age):
 3         self.name = name
 4         self.age = age
 5     def __str__(self):
 6         return  "<class:Person Name:%s>"%self.name
 7     def __repr__(self):
 8         return "<Name:%s>"%self.name
 9     def __len__(self):
10         return self.age
11 tom = Person("Tom",20)
12 print repr(tom)            
13 print tom
14 print len(tom)

技術分享圖片

當然還有很多:

 1 def __iter__(self):#重寫內建叠代功能
 2     ret = do_something()
 3     return ret  
 4 
 5 def __getitem__(self):#增加下表取對象功能
 6     pass
 7 
 8 def __getattr__(self):#增加取自身屬性的處理
 9     pass
10 
11 def __call__(self):#直接實例當做函數調用
12     pass
13 """
14 class A:
15     def __call__(self):
16          print "ok"       
17 a = A()
18 a()
19 >>> ok
20 """

三、@property方法屬性化:

 1 class student:
 2     def __init__(self,name):
 3         self.name = name
 4     @property
 5     def age(self):
 6         return self.age
 7     @age.setter
 8     def age(self,age):
 9         self.age = age
10 
11 """
12 a = student("stu")
13 a.age = 20
14 a.age
15 >>> 20
16 """

Python class的屬性訪問控制和內建函數重寫實現高級功能以及@property