Hello,
I would like to do something like:
class Hi():
def read(self):
return 23
hi = Hi()
val1 = Hi.read()
val2 = Hi
I would like to associate the function
read()
or whatever returns when I do an equal from the object Hi. In the example
val1
and
val2
would have the same value.
Is that posible in Python?
Thanks!
Hello,
I don't want to do a comparison, I just want to assign a value within the object without using the .method and read the attribute in the same way. Something like:
class Reg():
register = 0
def write(val):
self.register = val
def read():
return self.register
def __assign__(self, value):
self.register = value
reg = Reg()
reg = 5 # Now register is 5, this is equivalent to:
reg.write(5)
val = reg.read()
val = reg # <- This is that I want to archieve,
When I write val = reg I want to read the register value within the reg object. I mean to be equivalent to reg.read(), is it possible to overwrite the behaviour of the "=" in such a way?
Thanks
(Jul-09-2019, 08:47 PM)ihouses Wrote: [ -> ]is it possible to overwrite the behaviour of the "=" in such a way?
No. You could only do it with item or attribute assignment, which is what you are trying to avoid in the first place.
You could do it this way
class Reg():
register = 0
def write(self, val):
self.register = val
r = Reg()
r.write(3)
val = r.register
print(val)
Output:
3