2013-04-05 65 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