Return a value when I equal an object from a class - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Return a value when I equal an object from a class (/thread-19672.html) |
Return a value when I equal an object from a class - ihouses - Jul-09-2019 Hello, I would like to do something like: class Hi(): def read(self): return 23 hi = Hi() val1 = Hi.read() val2 = HiI 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! RE: Return a value when I equal an object from a class - Yoriz - Jul-09-2019 Give your class the __eq__ method.https://docs.python.org/3/reference/datamodel.html?highlight=__eq__#object.__eq__ Wrote:object.__lt__(self, other) RE: Return a value when I equal an object from a class - ihouses - Jul-09-2019 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 RE: Return a value when I equal an object from a class - ichabod801 - Jul-09-2019 (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. RE: Return a value when I equal an object from a class - SheeppOSU - Jul-10-2019 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)
|