Python Forum
Get name of instanciated class from class itself
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Get name of instanciated class from class itself
#1
when I create an instance of a class,
I'm thinking that the new object is somewhere on the call stack,
during the instantiating process. Is it possible  to access that name without actually passing it
as part of the init process.
For example in the following routine, I want to extract the value
Bob:
class MyClass(object):
    def __init__(self, starting_index=0):
        '''
        Initialization
        :param starting_index: optional initial starting index
        '''
        self.current_index = starting_index
        # The following gives me the name of self, this class
        print(self.__class__.__name__)
        # How can I get the name of an instantiating object (Bob) here?

def testit():
    Bob = MyClass()

if __name__ == '__main__':
    testit()
Reply
#2
Only for better understanding:
How looks the solution if passing is allowed as part of the init process ?
Reply
#3
Quote:Is it possible  to access that name without actually passing it as part of the init process.
I know I can do it that way, but from my compiler writing days, assume that there is a memory pointer
involved when instantiating the class. This is usually kept on the heap, so should be available.
Reply
#4
No . I believe there isn't a way.
Bob is a local variable that points to the object.
The __init__ of a class returns object pointer

Curious why do you want the name ?
99 percent of computer problems exists between chair and keyboard.
Reply
#5
Maybe this helps:
http://effbot.org/pyfaq/how-do-i-get-a-l...-class.htm
Reply
#6
Thanks, I knew that I could do that.
The effbot page is a dated one, and I believe I looked at that several years ago. It's still interesting.
I now I can work around it, it was just a curiosity.

In C, (before C++ was coined) we still had classes, but we didn't call them that.

They were structure typedefs, and instantiated by creating a pointer to the new type.

During the precompile process, that pointer would have had a reference in the symbol table,
but normally (unless building for debug) was removed after the program was compiled.

So I didn't think it would be available in python either, but decided to ask anyway.
Reply
#7
Ok, so I was messing around with the inspect module, because I actually didn't know if this was possible. On the one hand, objects are created before they're assigned to a variable, but on the other hand, python's parser already "knows" where things are going before they're created, so... **shrug**

Anyway, it IS possible, but it looks like an ugly hack, and it does... weird things if you're not assigning it to anything (since there's no name of the thing you're not assigning it to).

In order to avoid contaminating the stack/local variables, I started a new session:
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> class Spam:
...   def __init__(self):
...     stack_obj = inspect.stack()[-1]
...     names = stack_obj.frame.f_code.co_names
...     my_name = names[-1]
...     print(my_name)
...
>>> bob = Spam()
bob
>>> your_mom = Spam()
your_mom
>>> Spam()
Spam
<__main__.Spam object at 0x03E2FB70>
>>> [Spam() for _ in range(5)]
range
range
range
range
range
[<__main__.Spam object at 0x03E2FBD0>, <__main__.Spam object at 0x03E2FBF0>, <__main__.Spam object at 0x03E2FB50>, <__main__.Spam object at 0x03E2FAF0>, <__main__.Spam object at 0x03E2FBB0>]
Reply
#8
Quote:but it looks like an ugly hack, and it does... weird things
That's typical of inspect, but I'm still very glad it's there.
I played around with it for several days some time back.
Every time I thought I had it totally figured out, I discovered something new.

Import is another one, it's a lot better since re-written by Brett Cannon, but
still a mind bender.

'Brain surgery while you wait'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 6 356 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  class definition and problem with a method HerrAyas 2 253 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Printing out incidence values for Class Object SquderDragon 3 291 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  class and runtime akbarza 4 368 Mar-16-2024, 01:32 PM
Last Post: deanhystad
  Operation result class SirDonkey 6 533 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  The function of double underscore back and front in a class function name? Pedroski55 9 665 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  super() and order of running method in class inheritance akbarza 7 737 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Class test : good way to split methods into several files paul18fr 4 485 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Good class design - with a Snake game as an example bear 1 1,836 Jan-24-2024, 08:36 AM
Last Post: annakenna
  question about __repr__ in a class akbarza 4 612 Jan-12-2024, 11:22 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020