2011-06-25 146 views
22

在python中定義一個具有類作用域的全局變量的正確方法是什麼?全局變量Python類

從C/C++/Java的背景的我認爲這是正確的:

class Shape: 
    lolwut = None 

    def __init__(self, default=0): 
     self.lolwut = default; 
    def a(self): 
     print self.lolwut 
    def b(self): 
     self.a() 
+4

如果下面的答案是正確的,你應該接受它作爲 – Clintm

回答

53

你有什麼是正確的,但你不會把它叫做全球,它是一類屬性,可以訪問通過類例如Shape.lolwut或通過例如例如shape.lolwut但要小心,同時設置它,因爲它會設置一個實例級屬性不是階級屬性

class Shape(object): 
    lolwut = 1 

shape = Shape() 

print Shape.lolwut, 
print shape.lolwut, 

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance 
shape.lolwut = 2 

print Shape.lolwut, 
print shape.lolwut, 

# to change class attribute access it via class 
Shape.lolwut = 3 

print Shape.lolwut, 
print shape.lolwut 

輸出:

1 1 1 2 3 2 

有人可能希望輸出爲1 1 2 2 3 3,但它是不正確的

+1

我測試你的例子在python 2.7,沒關係。但是當你第一次爲Shape.lolwut設置值時,實例值將被改變。一旦你將值設置爲實例屬性,即使你改變了類級別的值,這兩者也不會相同,就像你的例子一樣。 – x4snowman

+0

@Dunun我也測試過。我看到了與你所提到的相同的情況。你知道爲什麼會這樣嗎?當您從類級別更改屬性時,也會更改實例。但是,當您首先更改實例級別時,然後從Class級別更改時,它不會再影響實例。 – user1167910

+0

@ user1167910參考python文檔https://docs.python.org/2.7/reference/datamodel.html,你會發現'屬性賦值和刪除更新實例的字典,從來沒有一個類的字典' – x4snowman