2012-07-27 53 views

回答

4

其指定爲屬性類:

>>> class MyClass(object): 
    def __init__(self, x=None): 
     if x is not None: 
      self.__class__.x = x 
    def do_something(self): 
     print self.x # or self.__class__.x, to avoid getting instance property 

>>> my_class1 = MyClass('aaa') 
>>> my_class2 = MyClass() 
>>> my_class2.do_something() 
aaa 
+0

謝謝,非常好 – 2012-07-27 12:11:43

+0

@ChZeeshan:不客氣。 – Tadeck 2012-07-27 12:13:08

0

你不行。您可以使用類屬性代替:

class Klass: 
    Attr = 'test' 

# access it (readonly) through the class instances: 
x = Klass() 
y = Klass() 
x.Attr 
y.Attr 

Read more關於Python類。

+0

但我需要在運行時設定x的值。有沒有其他方法可以做到這一點? – 2012-07-27 12:05:20

+0

@ChZeeshan:是的,你可以將它分配給類,而不是實例。 – Tadeck 2012-07-27 12:07:34

3

在Python中沒有靜態變量,但你可以使用類變量爲。這裏有一個例子:

class MyClass(object): 
    x = 0 

    def __init__(self, x=None): 
     if x: 
      MyClass.x = x 

    def do_something(self): 
     print "x:", self.x 

c1 = MyClass() 
c1.do_something() 
>> x: 0 

c2 = MyClass(10) 
c2.do_something() 
>> x: 10 

c3 = MyClass() 
c3.do_something() 
>> x: 10 

當你調用self.x - 它首先爲實例級變量,實例化爲self.x,如果沒有發現 - 然後尋找Class.x。因此,您可以在課堂級別上定義它,但在實例級別上覆蓋它。

廣泛使用的例子是使用具有可能的超控默認類變量成實例:

class MyClass(object): 
    x = 0 

    def __init__(self, x=None): 
     self.x = x or MyClass.x 

    def do_something(self): 
     print "x:", self.x 

c1 = MyClass() 
c1.do_something() 
>> x: 0 

c2 = MyClass(10) 
c2.do_something() 
>> x: 10 

c3 = MyClass() 
c3.do_something() 
>> x: 0 
相關問題