Akoi Meexx Akoi Meexx - 15 days ago 4x
Python Question

Getting an instance name inside class __init__()

While building a new class object in python, I want to be able to create a default value based on the instance name of the class without passing in an extra argument. How can I accomplish this? Here's the basic pseudo-code I'm trying for:

class SomeObject():
defined_name = u""

def __init__(self, def_name=None):
if def_name == None:
def_name = u"%s" % (<INSTANCE NAME>)
self.defined_name = def_name

ThisObject = SomeObject()
print ThisObject.defined_name # Should print "ThisObject"


Instances don't have names. By the time the global name ThisObject gets bound to the instance created by evaluating the SomeObject constructor, the constructor has finished running.

If you want an object to have a name, just pass the name along in the constructor.

def __init__(self, name):
    self.name = name