Why did I get a wrong result from code like `instance.method`?

Question:

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 of p2 are different. I just want p2 as a point which is the reflected point of p1 from x-axis. How can I do it?

Asked By: arnobpl

||

Answers:

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.

Answered By: Celada

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)
Answered By: WooParadog

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().

Answered By: cyrusin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.