2013-04-05 67 views
1

我想要一個具有一些類變量的類,並具有對這些變量執行內容的函數 - 但我希望函數能夠自動調用。有沒有更好的方法來做到這一點?我應該使用init嗎?對不起,如果這是一個不好的問題 - 我對Python很新。創建類的實例python&__init__

# used in second part of my question 
counter = 0  

class myClass: 
    foo1 = [] 
    foo2 = [] 

    def bar1(self, counter): 
     self.foo1.append(counter) 
    def bar2(self): 
     self.foo2.append("B") 

def start(): 
    # create an instance of the class 
    obj = myClass() 
    # I want the class methods to be called automatically... 
    obj.bar1() 
    obj.bar2() 

# now what I am trying to do here is create many instances of my class, the problem is 
# not that the instances are not created, but all instances have the same values in 
# foo1 (the counter in this case should be getting incremented and then added 
while(counter < 5): 
    start() 
    counter += 1 

那麼有沒有更好的方法來做到這一點?並導致我的所有對象具有相同的值?謝謝!

+1

foo1和foo2是類變量,它們由所有對象共享,如果您希望它們對所有對象都是分離的,請創建'__init__'方法並在函數 – avasal 2013-04-05 05:00:38

+0

中初始化它們。Thanks - 編輯它。因此,如果它們在'__init__'中,並且我創建了obj1,然後創建了obj2,那麼它們都將變量設置爲'__init__'中的任何值,就像它們只是在類定義中一樣,obj1.doSomething() obj2將使用的變量? (假設doSomething()改變一個類變量) – Joker 2013-04-05 05:05:45

+0

- 注意:這在下面得到了回答:請參閱@avasal – Joker 2013-04-05 05:10:17

回答

4

foo1和foo2的是類變量,它們被所有對象共享,

類應該是這樣的,如果你想foo1foo2要爲每個對象不同:

class myClass: 
    # __init__ function will initialize `foo1 & foo2` for every object 
    def __init__(self): 
     self.foo1 = [] 
     self.foo2 = [] 

    def bar1(self, counter): 
     self.foo1.append(counter) 
    def bar2(self): 
     self.foo2.append("B") 
+0

非常感謝 - 清除了我對'__init__'方法的困惑。 – Joker 2013-04-05 05:11:16

+1

如果解決了您的問題,請接受答案。 – avasal 2013-04-05 05:29:18