I have a class with the following structure:
class Example:
def __init__(self, value, foo):
self.value = value
self.foo = foo
self.bar = self.modify_stuff(value, foo)
def modify_stuff(self, value, foo):
""" some code """
pass
I want to create an instance of the class, and then be able to refer to value
directly, like this:
ex = Example(3, 'foo')
ans = 5 ex
Instead of:
ans = 5 ex.value
How can I do this?
CodePudding user response:
Rewrite the add and radd:
class Example:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, Example):
return self.value other.value
return self.value other
def __radd__(self, other):
if isinstance(other, Example):
return self.value other.value
return self.value other
print(Example(3) 5)
print(Example(4) Example(2))
# 8
# 6