-3
class Point:
    def __init__(self, x = 0, y = 0):
        self.x, self.y = x, y
        print "New Point object", self, "constructed"

    def __str__(self):
        return "(" + str(self.x) + "," + str(self.y) + ")"

    def __del__(self):
        print "Destructor"

pt1 = Point()

Output:

New Point object (0,0) constructed

Method functions receive a special first argument, called self by very strong convention, which is the instance object that is the implied subject of the method call, and gives access to instance attributes.

So why is self in init() printing (0, 0) instead of pt1? Isn't pt1 the instance object?

Leponzo
  • 624
  • 1
  • 8
  • 20
  • 1
    That's because you've explicitly defined how the thing is to be printed. See http://stackoverflow.com/a/592849/1443496 if you want this functionality. – Sean Allred Nov 20 '14 at 13:56
  • 3
    `pt1` is simply the name to which the object is assigned, it has **no connection** to the object's identity or display (indeed, the object doesn't "know" that's what you think its name is). See e.g. http://nedbatchelder.com/text/names.html – jonrsharpe Nov 20 '14 at 14:02

3 Answers3

4

You're explicitly telling the Point object to display itself as (x,y) when you define the __str__ method. In order for the print to work it must convert itself to a string, and it does that by calling the __str__ method.

Notice what happens when you remove the __str__ method:

New Point object <__main__.Point instance at 0x1005da488> constructed

In this case, python must still convert the object to a string in order to print it, but since there is no explicit definition of __str__ it uses it's own default implementation.

In either case, the object itself doesn't know it was assigned to pt1 so it has no way of printing that information. In fact, the same object could be assigned to multiple variables, or none at all (ie: it could be a member of a list).

Here's the link to the python 2.7 documentation on __str__:

https://docs.python.org/2/reference/datamodel.html#object.str

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

It is printing (0,0) because that is how the __str__ method is defined.

def __str__(self):
    return "(" + str(self.x) + "," + str(self.y) + ")"

It prints self.x and self.y along with some formatting.

And since you instatiated the Point as

pt1 = Point()

It will use the default arguments 0 and 0 from the __init__ method

def __init__(self, x = 0, y = 0):

So it is working exactly as intended.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

That's because you've explicitly defined how the thing is to be printed. See How can you print a variable name in python? if you want the functionality you describe.


If your interested in introspection, explore everything in dir(pt1).

Community
  • 1
  • 1
Sean Allred
  • 3,558
  • 3
  • 32
  • 71