msc87
msc87

Reputation: 1029

how to reach to the instance name of a class?

I am a quit new python programer and just for curiosity I want to know how I can reach to the name of instance which is made in the body of main,in the methods of my class . I want to know whether there is a built-in method for classes or I should manage it myself. by the way, I don't want to use lists or Dictionaries. a sample code is following:

class Vec2D(object):
   def __init__(self,X, Y):
     self.x=X
     self.y=Y
     print "X coordinate is ",self.x # I want to add it here 
     print "Y coordinate is ",self.y # and here

if __name__ == '__main__':
    mypoint1 = Vec2D(0,1)
    mypoint2 = Vec2D(1,2)

It could be considered as a reporting issue...

Upvotes: 0

Views: 365

Answers (3)

martineau
martineau

Reputation: 123443

Well, for starters, you couldn't print the name in __init__() because the object is still being constructed and hasn't been assigned one yet. Even if it were, there's no built-in way to find out what it is in Python.

However it is possible to search for the object after construction in the module's global namespace, which allows you to do things like this:

class Vec2D(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        my_name = '<unknown>'
        namespace = globals().copy()
        for name,obj in namespace.items():
            if obj is self:
                my_name = name
                break
        return "\n".join(["{!r}:",
                          "  X coordinate is {}",
                          "  Y coordinate is {}"]).format(my_name, self.x, self.y)

if __name__ == '__main__':
    mypoint1 = Vec2D(0,1)
    mypoint2 = Vec2D(1,2)

    print mypoint1
    print mypoint2

Output:

'mypoint1':
  X coordinate is 0
  Y coordinate is 1
'mypoint2':
  X coordinate is 1
  Y coordinate is 2

However this isn't foolproof because if there are two names for the same object, the for search loop will stop as soon as it finds one of them. It could be modified to find them all, I suppose...

Upvotes: 1

Timothy
Timothy

Reputation: 4487

As @MartijnPieters said, these's no way to get the variable name of an instance. The names are not kept after interpreting.

But if you do have the special need, I think there're at least 2 approaches for you.

Let's say you have an instance MyInstance of class MyClass, then

  1. str(MyInstance) will give you a string like <__main__.MyClass instance at 0x1044b6f80>, it uniquely indicates MyInstanceduring the runtime. You might want to use it as the name of the instance.

  2. Explicitly define a "name" in the construction of the class, like:

    class MyClass:
        def __init__(self, name):
            self.name = name
    

    . Afterwards you can always get the name by:

    MyInstance = MyClass("Instance1")
    print MyInstance.name
    

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121584

You can't. A value has no way to know what variable refers to it.

The reason is quite simple; you can have multiple variables refer to the same value:

mypoint3 = mypoint1

Now what name does the instance have?

Upvotes: 3

Related Questions