We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,001 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

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

4
Contributors
6
Replies
1 Day
Discussion Span
2 Years Ago
Last Updated
8
Views
Question
Answered
Peter_TARAS
Newbie Poster
8 posts since Nov 2008
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 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")
Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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
woooee
Posting Maven
2,705 posts since Dec 2006
Reputation Points: 827
Solved Threads: 779
Skill Endorsements: 9

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

Peter_TARAS
Newbie Poster
8 posts since Nov 2008
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 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

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)
Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

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
woooee
Posting Maven
2,705 posts since Dec 2006
Reputation Points: 827
Solved Threads: 779
Skill Endorsements: 9
Question Answered as of 2 Years Ago by woooee and Gribouillis

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
"""
vegaseat
DaniWeb's Hypocrite
Moderator
6,475 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0719 seconds using 2.71MB