简体   繁体   中英

How to return the same class object in Python

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?

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM