3

I would like to know if this is possible/how it is possible.

I have a Python object class:

class myClass(object):
    def __init__(self):
        ...do something

Then I create an instance of that object:

myObjectClass = myClass()

From within myClass, is it possible to get the "name" of the variable (myObjectClass) as a string?

Thanks, Adam

tmthydvnprt
  • 10,398
  • 8
  • 52
  • 72
user2387315
  • 107
  • 3
  • 10
  • 1
    Why do you need to do this? – Blender Nov 10 '13 at 21:25
  • 3
    What should be the output for: `a_tuple = (myClass(), 1)`? What about `some_instances = [myClass(), myClass(), myClass()]`? What you describe is not even *well defined*, hence it's impossible to find a solution. Even if you want to consider only the `identifier = myClass()` simple case, what about `a = b = myClass()`? Or `a = myClass(); b = a; del a`? And what about `a = myClass(); a_list = [a]; del a`? You should describe how these simple cases should be handled. Anyway it simply cannot be done and isn't useful at all. By the way: you fell victim of the [XY problem](http://bit.ly/olPTFK). – Bakuriu Nov 10 '13 at 21:33
  • See my original post here: stackoverflow.com/a/59364138/5088165 – Panwen Wang Apr 20 '20 at 19:19

3 Answers3

5

No, it isn't possible, in any reasonable manner, and also multiple variables may point to the same object. It's also not possible at all in respect of local variables. Whatever problem you're actually trying to solve, this is the wrong way to go about it.

Also, sort out your understanding of the difference between an object or instance and a class.

Marcin
  • 48,559
  • 18
  • 128
  • 201
2

It's definitely not possible, other than some hackish way.

Why not just add a name parameter to init, like this:

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

myObjectClass = myClass("myObjectClass")

This is how I'd actually do it..

  • 1
    Well, what does that buy you? I'm not saying this is the wrong way to do this - rather it's the right way to do what is probably the wrong thing. – Marcin Nov 10 '13 at 21:38
  • As you said it's the right way to do a wrong thing. It's pretty `useless` and `stupid`, I'm not sure what's his purpose of doing such a thing. –  Nov 10 '13 at 21:44
  • there is not much difference between `self.name` as `self`, and latter is not name, but pointer, and is sufficient for addressing. what else are names used for? – latheiere Nov 10 '13 at 22:09
1

You could do:

obj = MyClass()

the_globals = globals()
for o in the_globals:
    if the_globals[o].__class__.__name__ == 'MyClass':
        print 'yay', o

But you really don't want to do this.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180