How to return the same class object in Python
Solution 1
I just want p2 as a point which is the reflected point of p1 from x-axis. How can I do it?
Well, then you should call the method reflect_x
on p1
and store the result in p2
, like this:
p2 = p1.reflect_x()
In your sample code, you did something different:
p2 = p1.reflect_x
which means you want p2
to contain p1
's reflect_x
method.
Solution 2
FYI:
If you want to access reflect_x
as a member instead of as a method. add @property
decorator to reflex_x
method.
like:
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)
@property
def reflect_x(self):
return Point(self.x,-self.y)
Solution 3
In python, every name is reference, every thing is object, even it is function or method.
You just use the name p1.reflect_x
, this is just a reference of an instancemethod object, which is bound to instance p1
. So when you use p2 = p1.reflect_x
, you just assign a reference to p2
, and never call the method yet.
According to this, the statement return Point(self.x, -self.y)
never run in fact. If you want to run it just call the method with this: p2 = p1.reflect_x()
.
arnobpl
I am currently a Research Assistant at University at Buffalo. My research interest includes Security and Privacy, Computer Network, Operating System, Computer Architecture, Embedded System, Cloud Computing. I have completed my B.Sc. in Computer Science and Engineering from Bangladesh University of Engineering and Technology. I have also worked as a Software Engineer in Reve Systems.
Updated on July 14, 2022Comments
-
arnobpl almost 2 years
It is a basic question. I have written the following code:
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 reflect_x(self): return Point(self.x,-self.y) p1=Point(3,4) p2=p1.reflect_x print(str(p1),str(p2)) print(type(p1),type(p2))
Here type of
p1
and type ofp2
are different. I just wantp2
as a point which is the reflected point ofp1
from x-axis. How can I do it?-
Michael Hawkins almost 11 yearsPlease wrap your code in a codeblock.
-
abarnert almost 11 yearsPlease don't just describe the results, show them. In this case, your error was so obvious that Celada found it in under a minute, but usually that isn't true just from glancing at the code. That's why seeing the results (
p2
being a "bound method" instead of an "instance") is useful to people trying to diagnose your problem.
-
-
arnobpl almost 11 yearsThank you very much! I was really stuck in it! Now I have got the solution.
-
arnobpl almost 11 yearsThanks for nice explanation!