Reputation: 11
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?
Upvotes: 0
Views: 93
Reputation: 44485
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
Upvotes: 3