Joker
Joker

Reputation: 2229

Creating instances of classes python & __init__

I want a class that has some class variables, and has functions that perform stuff on those variables - but I want the functions to be called automatically. Is there a better way to do it? Should I be using init for this? Sorry if this is a nooby question - I am quite new to 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

So is there a better way to do this? And is causing all of my objects to have the same values? Thanks!

Upvotes: 1

Views: 123

Answers (1)

avasal
avasal

Reputation: 14854

foo1 and foo2 are class variables, they are shared by all the objects,

your class should look like this, if you want foo1, foo2 to be different for every object:

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")

Upvotes: 4

Related Questions