0

I am learning python. Suppose I have my Class named Dog, and two instances named Fido and Molly. I want to change an attribute of second instance by overloading + operator with __add__ so when I type Fido+Molly the Molly.touched attribute will be set. How is accessing from one instance to another instance's attributes deployed in python?

0

1 Answer 1

3

I think you are interested in how the __add__ special method works. In essence it works as x.__add__(y) where x and y can be instance objects. See an example of it's implementation here.

You would need to overload __add__() in Dog to return something that updates the y.touched attribute. Example:

class Dog(object):

    def __init__(self, touched):
        self.touched = touched

    def __add__(self, other):
        other.touched = other.touched + self.touched 
        #return None                                    # optional, explicit

fido = Dog(1)
molly = Dog(2)

fido + molly
molly.touched
# 3
Sign up to request clarification or add additional context in comments.

2 Comments

return None is redundant, by the way.
Yes, but it is explicit for someone unfamiliar with Python. I will make a comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.