Rio mario
Rio mario

Reputation: 283

variable defined inside __init__ not reading

What I have understood is to define variables inside init magic method. I did but the next method is not reading it.

Any help?

class Foo:

    var = 9

    def __init__(self, a, b):
        self.i = a
        self.j = b

    def add(self, a, b):
        print a+b

bar = Foo(5, 5)  # create object

print bar.var  # access class variable

o/p:

9

Why does it not print

10

9

Upvotes: 0

Views: 117

Answers (2)

merlin2011
merlin2011

Reputation: 75579

If you want to run the code inside add, you must call it.

bar = Foo(5, 5)  # create object
bar.add(5,5)
print bar.var  # access class variable

Upvotes: 3

KSFT
KSFT

Reputation: 1774

You called the variables self.i and self.j, not a and b, so that's how you need to refer to them. add() should be defined like this:

def add(self):
    print self.i+self.j

Upvotes: 3

Related Questions