I have following code:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
point = Point.zero()
I am not getting the expected output: Point(0, 0)
.
CodePudding user response:
you are getting the correct Point
object. To confirm, print type(point)
and print point.x
or point.y
. But its representation defaults to what object.__repr__
provides(all classes inherit this from object
class). Implement your own __str__
or __repr__
. (See the difference here):
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
def __repr__(self) -> str:
return f"Point{self.x, self.y}"
point = Point.zero()
print(point)
CodePudding user response:
You do, but what you generate is a Class Object:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def zero(cls):
return cls(0, 0)
origin = Point.zero()
origin.x -> 0
origin.y -> 0