简体   繁体   中英

Python -- __str__ does not work on import

I'm new to Python but I've been having this problem similar to this thread

I'm currently running:

Python 3.6.7
GCC 8.2.0
No IDE just plain *.py files

Here's my class:

class Point:                                                                                                                                  
    """ Point class represents and manipulates x,y coordinates """

    def __init__(self, x=0, y=0):                                                   
        """ Create a new point at the origin """                                    
        self.x = x                                                                  
        self.y = y                                                                  

    def __str__(self):                                                              
        return "({0}, {1})".format(self.x, self.y)   

p = Point()
print(p)  

I was curious why the __str__ works on the same file but returns:

<point.Point object at 0x7eff98cc4c18> 

after I imported to another.py file

My import file is this:

from point import Point
p = Point()
print(p)

I appreciate any input

Edit: The code I have here is all the code I've used to reproduce the bug. My guess is that this might be an error in my setup with Python3 in Ubuntu

Works OK for me.

$ python --version
Python 3.6.5
$ python Point.py 
(0, 0)
$ python
Python 3.6.5 (default, Nov 18 2018, 02:06:39) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from Point import Point
(0, 0)
>>> p = Point()
>>> p
<Point.Point object at 0x7fe04d5470f0>
>>> print(p)
(0, 0)
>>> 

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