How to get the name of an object from a class?

I have a simple class from which I create two objects. Now I want to print the name of the object from the class. So something like this:

class Example: def printSelf(self): print self object1 = Example() object2 = Example() object1.printSelf() object2.printSelf() 

I need this to print:

 object1 object2 

Unfortunately, this just prints <myModule.Example instance at 0xb67e77cc>

Does anyone know how I can do this?

+4
source share
3 answers

object1 is just an identifier (or variable) pointing to an instance object, objects have no names.

 >>> class A: ... def foo(self): ... print self ... >>> a = A() >>> b = a >>> c = b >>> a,b,c #all of them point to the same instance object (<__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>) 

a , b , c are just links that allow us to access the same object, when the object has 0 , it automatically collects garbage.

A quick hack would be to pass the name when creating the instance:

 >>> class A: ... def __init__(self, name): ... self.name = name ... >>> a = A('a') >>> a.name 'a' >>> foo = A('foo') >>> foo.name 'foo' >>> bar = foo # additional references to an object will still return the original name >>> bar.name 'foo' 
+5
source

The object has no name. A variable that refers to an object is not the "name" of the object. An object cannot know about any of the variables that relate to it, not least because the variables are not a first-class language subject.

If you want to change the printing method of this object, override either __repr__ or __unicode__ .

If this is for debugging purposes, use a debugger. What is this for.

+4
source

A common way to do this is something like that:

 class Example(object): def __init__(self,name): self.name=name def __str__(self): return self.name object1 = Example('object1') object2 = Example('object2') print object1 print object2 

Print

 object1 object2 

However, there is no guarantee that this object remains bound to the original name:

 object1 = Example('object1') object2 = object1 print object1 print object2 

Prints object1 , as expected, twice. If you want to see things under the hood, use a debugger.

+1
source

Source: https://habr.com/ru/post/1487127/


All Articles