1

我想要一个具有一些类变量的类,并且具有对这些变量执行操作的函数——但我希望这些函数能够被自动调用。有更好的方法吗?我应该为此使用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

那么有没有更好的方法来做到这一点?并导致我所有的对象都具有相同的值?谢谢!

4

1 回答 1

4

foo1 和 foo2 是类变量,它们被所有对象共享,

foo1如果你愿意的话,你的类应该像这样foo2对每个对象都不同:

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")
于 2013-04-05T05:02:49.030 回答