class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.coord = (self.x, self.y)
def __add__(self, other):
return Point(self.x other.x, self.y other.y)
p1 = Point(3, 5)
p2 = Point(7, -2)
print(p1 p2) # <__main__.Point object at 0x000001A2DAEF3E20>
If i return like this i got this result. (I know this is the memory address)
But if i return like this:
return self.x other.x, self.y other.y
Then I got the actual values (10, 3)
And I don't really understand that I am doing when i type there the name of the class
CodePudding user response:
When you type the name of the class, you're invoking the class constructor to construct a new Point
object:
Point(self.x other.x, self.y other.y)
When you remove the Point()
part, you're just constructing a tuple
:
self.x other.x, self.y other.y
The tuple
prints nicely, but it's not a Point
; if you try to add it to another tuple
you'll get a concatenated tuple
:
>>> (3, 5) (7, -2)
(3, 5, 7, -2)
and if you try to add it to a Point
you'll get an error:
>>> (3, 5) Point(7, -2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "Point") to tuple
What you might want to do is add a __str__
and/or __repr__
method to your Point
class so that when you print it, you see x
and y
rather than the memory address:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.coord = (self.x, self.y)
def __add__(self, other):
return Point(self.x other.x, self.y other.y)
def __str__(self):
return f"Point({self.x}, {self.y})"
Now you can return a Point
object and print it in a way that's more useful:
p1 = Point(3, 5)
p2 = Point(7, -2)
print(p1 p2) # Point(10, 3)
You might also consider using a dataclass
, which automatically defines __init__
and __repr__
in ways that are convenient for this type of use case (I'd also make coord
a @property
so you don't need to worry about updating it every time x
and y
change):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
@property
def coord(self):
return self.x, self.y
def __add__(self, other):
return Point(self.x other.x, self.y other.y)
p1 = Point(3, 5)
p2 = Point(7, -2)
print(p1 p2) # Point(x=10, y=3)
CodePudding user response:
I think what you want is this:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
self.coord = (self.x, self.y)
def __add__(self, other):
return Point(self.x other.x, self.y other.y)
p1 = Point(3, 5)
p2 = Point(7, -2)
print(p1 p2)
this will return you a Point instance tuple of coord 10, 3