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