1

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
arnobpl
  • 1,126
  • 4
  • 16
  • 32
  • 1
    Please wrap your code in a codeblock. – Michael Hawkins Jul 04 '13 at 01:17
  • 1
    Please 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. – abarnert Jul 04 '13 at 01:22

3 Answers3

6

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.

Celada
  • 21,627
  • 4
  • 64
  • 78
4

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)
WooParadog
  • 645
  • 4
  • 7
2

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

glglgl
  • 89,107
  • 13
  • 149
  • 217
cyrusin
  • 21
  • 3