user2569165
user2569165

Reputation:

Need help walking through logic of this code

I'm pretty new with Python and programming in general, so excuse the lack of "fu". :)

I'm having trouble understanding this class call:

snippet

class bar:
    def __init__(self, a):
        self.a = a
    def __add__(self, b):
        s = self.a + b.a
        return s

end snippet

So, from the interpreter, if I issue:

x = bar(10)
y = bar(20)
z = x + y
print(z)

I get '30' back. That's correct.

I see how self.a is created, but I don't understand how b.a is getting created to do the addition.

Any guidance is appreciated.

Upvotes: 3

Views: 83

Answers (3)

xgord
xgord

Reputation: 4776

x = bar(a) creates an object of the class bar with an a value of 'a'. Each bar object has a property/variable named a.

In x + y, the function add of x is called using y as the parameter.

So b = y, meaning b.a = y.a = 20.

Upvotes: 0

Slater Victoroff
Slater Victoroff

Reputation: 21904

In this code, b.a isn't being created, it is being accessed. You're basically passing in y as the argument b, which already has an a attribute associated with it since it is an object of type bar. If you want to step through your code go to http://www.pythontutor.com

Upvotes: 3

mishik
mishik

Reputation: 10003

When you call x + y it is actually translated to:

x.__add__(y)

Therefore, this method is called:

__add__(self, b)  # __add__(x, y)

Which results in:

s = x.a + y.a     # 30
return 30

Upvotes: 4

Related Questions