+ 3

Which method is getting called for assignment in python class object?

Here __call__ method is called when we write p2(p) then which method is called when we use p2 = p? if we don't write __call__ then p2(p) creates an error and that is fine. what if I want to disallow p2 = p? class Point: def __init__(self, x = 0, y = 0): self.x = x self.y = y def __str__(self): return "({0},{1})".format(self.x,self.y) def __repr__(self): return "({0},{1})".format(self.x,self.y) def __add__(self,other): x = self.x + other.x y = self.y + other.y return Point(x,y) def __sub__(self,other): x = self.x - other.x y = self.y - other.y return Point(x,y) def __mul__(self,other): x = self.x * other.x y = self.y * other.y return Point(x,y) def __call__(self,other): print("__call__") self.x = other.x self.y = other.y p = Point(1,3) p2 = Point() p2(p) print(p2) Result: __call__ (1,3)

12th Sep 2018, 8:56 PM
$±𝐎â‚č𝔭!𝐹𝓝
$±𝐎â‚č𝔭!𝐹𝓝 - avatar
4 Respostas
+ 9
You can't overload the assignment. However, you can overload the __setattr__ to restrict assigning new values to members of a class, if that suits you, instead.
12th Sep 2018, 9:16 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 12
12th Sep 2018, 9:36 PM
Modi
Modi - avatar
12th Sep 2018, 9:02 PM
$±𝐎â‚č𝔭!𝐹𝓝
$±𝐎â‚č𝔭!𝐹𝓝 - avatar
15th Sep 2018, 2:14 AM
$±𝐎â‚č𝔭!𝐹𝓝
$±𝐎â‚č𝔭!𝐹𝓝 - avatar