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

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")

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

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 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)
commented: good comment +12

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

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
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.