2009-06-19 72 views
3

我試圖學習描述符,並且被對象行爲困惑 - 在下面的兩個示例中,正如我理解的__init__他們應該工作一樣。有人可能會否認我,或者指出一個解釋這一點的資源?使用__init__和設置類變量之間的區別

import math 
class poweroftwo(object): 
    """any time this is set with an int, turns it's value to a tuple of the int 
    and the int^2""" 
    def __init__(self, value=None, name="var"): 
     self.val = (value, math.pow(value, 2)) 
     self.name = name 

    def __set__(self, obj, val): 
     print "SET" 
     self.val = (val, math.pow(val, 2)) 
    def __get__(self, obj, objecttype): 
     print "GET" 
     return self.val 

class powoftwotest(object): 
    def __init__(self, value): 
     self.x = poweroftwo(value) 

class powoftwotest_two(object): 
    x = poweroftwo(10) 


>>> a = powoftwotest_two() 
>>> b = powoftwotest(10) 
>>> a.x == b.x 
>>> GET 
>>> False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values? 
+0

您可能希望在輸出中包含類型(a.x)和類型(b.x)。 – 2009-06-19 17:05:57

回答

3

首先,請用LeadingUpperCaseNames命名所有類。

>>> a.x 
GET 
(10, 100.0) 
>>> b.x 
<__main__.poweroftwo object at 0x00C57D10> 
>>> type(a.x) 
GET 
<type 'tuple'> 
>>> type(b.x) 
<class '__main__.poweroftwo'> 

a.x是實例級訪問,它支持描述符。這就是3.4.2.2節「(所謂的描述符類)出現在另一個新式類的類字典中」的意思。類字典必須由實例訪問才能使用__get____set__方法。

b.x是類級訪問,它不支持描述符。

+0

如果描述符位於元類上,則類描述符可以支持類級訪問*。 – 2012-01-08 16:46:43

相關問題