创建类python&的实例__在里面__

时间:2013-04-05 04:59:22

标签: python oop class

我想要一个具有一些类变量的类,并且具有对这些变量执行操作的函数 - 但我希望自动调用这些函数。有没有更好的方法呢?我应该使用 init 吗?对不起,如果这是一个不起眼的问题 - 我对Python很新。

# 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 个答案:

答案 0 :(得分: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")