0

Possible Duplicate:
Getting an instance name inside class __init__()

I'm trying to solve this little problem:

class Test(object):
    def __init__(self):
        print "hello: %s" % i_dont_know

b = Test()
c = Test()

What I would like to get as a result:

hello: b
hello: c

Just the variable name.

I know that id(self) returns the reference code, it's possible to get the reference name ?

Community
  • 1
  • 1
  • i think vars is what you are looking at ,, i'll post answer if my code works right – Hamoudaq Feb 05 '13 at 21:16
  • Check this out http://stackoverflow.com/questions/1538342/how-can-i-get-the-name-of-an-object-in-python – TankorSmash Feb 05 '13 at 21:17
  • 2
    It's not possible, and it's the wrong question to begin with. Make it so you don't need it. –  Feb 05 '13 at 21:17
  • is it important to be at init ?? – Hamoudaq Feb 05 '13 at 21:20
  • Since it's in `__init__`, you *might* be able to inspect the stack and pull out the line of code which called the constructor and then parse the variable name out of that (in the simple case that you have above) ... But I'm not even going to bother trying to write up that solution since you really shouldn't need to do this ... – mgilson Feb 05 '13 at 21:27
  • EngHamoud: i tried the vars() no success delnan, mgilson: i don't care if "it's the wrong question", i just want to know if it's possible, python give's to me a LOT of possibilities, then ... – Jonathan Isaac Feb 05 '13 at 21:35

3 Answers3

1

No, you can't. What if I do this:

Test()

or this:

someList[3] = Test()

or this:

someList.append(Test())
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

No you can't. Besides the examples of BrenBarn, there is another insurmountable reason of why it's impossible. The constructor is completely executed before the assignment takes place.

Look at the bytecode:

>>> class Test(object): pass
... 
>>> def make_instances():
...     a = Test()
...     b = Test()
... 
>>> import dis
>>> dis.dis(make_instances)
  2           0 LOAD_GLOBAL              0 (Test)
              3 CALL_FUNCTION            0
              6 STORE_FAST               0 (a)

  3           9 LOAD_GLOBAL              0 (Test)
             12 CALL_FUNCTION            0
             15 STORE_FAST               1 (b)
             18 LOAD_CONST               0 (None)
             21 RETURN_VALUE 

The CALL_FUNCTION byte code is the one that executes __init__. STORE_FAST binds the object to the identifier. Python does not provide any way to interact with the binding, so there is no "special method" that could be used.

mgilson
  • 300,191
  • 65
  • 633
  • 696
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
1

It's probably best to do something like

class Test:
    def __init__(name):
        self.name = name


    def __str__():
        return name


a = Test("a")

print a    
>>> a
TankorSmash
  • 12,186
  • 6
  • 68
  • 106