justin cress
justin cress

Reputation: 1831

how do I write a class which allows instances to be introspected upon with __name__?

Writing a class Foo which allows its instances to return the names they were created with using __name__,

A = Foo(args)

str(A.__name__) 

should return 'A'

Upvotes: 0

Views: 64

Answers (1)

Remy Blank
Remy Blank

Reputation: 4285

That's not possible (at least, not in all cases and not without dirty tricks). In your example, A is a reference to an object of type Foo. The object has no knowledge of how references to it are stored. If you write:

A = Foo(args)
B = A

then A and B both reference the same object, and are totally indistinguishable, so you couldn't find which one was used to hold the first reference to the object. Of course, you could scan globals() for references to the object, and you would then find A and B. However, if you del A, all traces of A will have vanished.

What are you trying to do? If you explained the use case, maybe we could suggest an alternative solution than what you asked.

Upvotes: 6

Related Questions