1,105,352 Community Members

how to retrieve the name of an instance of a class as a string?

Member Avatar
Peter_TARAS
Newbie Poster
8 posts since Nov 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

Hi!

I designed a class in Python to do stuffs related to genetic algorithms. I have a method in this class, which should provide a sort of log to keep the track of the populations during the evolution. I mean, I provide the filename as a string argument to this method, and the method should create the log and place things in it. What I want to do is that in the case of setting the filename argument as an optional one (with the default value equal to None) to be able to use the name of the instance of that class as the filename. It makes sense to me because if I run multiple instances of this class I want to be able to save the results in files related to each instance. I know I can get the name of the class through instancename.__class__.__name__ but I want the instancename as a string.

Best regards

PTS

Member Avatar
Gribouillis
Posting Maven
3,454 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
0
 

The simplest idea would be to give your instance a member 'name' and pass this name when you create the instance, for example

class MyClass(object):
    def __init__(self, name, *args):
        self.name = name

my_instance = MyClass("GuidoVanRossum")
Member Avatar
woooee
Posting Maven
2,798 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

You can use the id also since you only want a name that is unique. Perhaps a dictionary with name/id --> class + args as well.

class TestClass(object):
    def __init__(self):
        print "class instantiated"
 
ins = TestClass()
unique_name = str(id(ins))
print unique_name
Member Avatar
Peter_TARAS
Newbie Poster
8 posts since Nov 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

The id retrieval idea looks good. Il give it a try. Maybe it would be possible, that knowing the object id, to retrieve its name.
Although it seems to be a practical way to solve my problem, I don't want to pass the name of the object to the instance itself as an argument because this is what I'm doing now.
The idea of a dictionary to hold the names and the objects id also sounds good. But I am curious about my original question: it is possible, from inside an instance of a class to retrieve the instance name? Let's say I've instantiated x as an instance of the class MyClass(); It is possible from inside x to retrieve "x" which is the name of the instance as a string?

Best regards,

PTS

Member Avatar
Gribouillis
Posting Maven
3,454 posts since Jul 2008
Reputation Points: 1,140 [?]
Q&As Helped to Solve: 884 [?]
Skill Endorsements: 18 [?]
Moderator
 
1
 

The id retrieval idea looks good. Il give it a try. Maybe it would be possible, that knowing the object id, to retrieve its name.
Although it seems to be a practical way to solve my problem, I don't want to pass the name of the object to the instance itself as an argument because this is what I'm doing now.
The idea of a dictionary to hold the names and the objects id also sounds good. But I am curious about my original question: it is possible, from inside an instance of a class to retrieve the instance name? Let's say I've instantiated x as an instance of the class MyClass(); It is possible from inside x to retrieve "x" which is the name of the instance as a string?

Best regards,

PTS

The instance doesn't have a name. When you write

x = MyClass()

x is not the name of the instance, x is a variable name in the local namespace, which is temporarily bound to your instance. If you call func(x) and func is defined by

def func(item):
  print(item)

func manipulates the same instance but it's bound to the local variable named 'item', so it is the same instance, but a different name.
If you need to identify your instance with a string, there are only 2 ways: either you explicitely create a name for the instance, or you build a name based on the instance's id. For example, you can build a name automatically like this:

class MyClass(object):
    def __init__(self):
        self.name = hex(id(self))

x = MyClass()
print(x.name)
Member Avatar
woooee
Posting Maven
2,798 posts since Dec 2006
Reputation Points: 783 [?]
Q&As Helped to Solve: 836 [?]
Skill Endorsements: 12 [?]
 
0
 

You would have to name it yourself via a class variable (shared by all instances of the class)

class TestClass(object):
    class_name = "TestClass"  ##  class variable
    def __init__(self):
        print "class instantiated"
 
print TestClass.class_name
ins = TestClass()
print TestClass.class_name
Question Answered as of 3 Years Ago by woooee and Gribouillis
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

Some more insight ...

import copy
import pprint

def funk():
    """
    wrote class inside function to keep local dictionary vars() clean
    """
    class C:
        pass

    bob = C()
    joe = C()
    pprint.pprint(vars())
    print('-'*50)
    # make a copy of vars() to freeze it
    vars_frozen = copy.copy(vars())
    for key in vars_frozen:
        if isinstance(eval(key), C):
            print(key)

funk()

""" result (Python26) >>
{'C': <class __main__.C at 0x00B497E0>,
 'bob': <__main__.C instance at 0x00B46738>,
 'joe': <__main__.C instance at 0x00B46EB8>}
--------------------------------------------------
bob
joe
"""
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: