instance name

Mark Winrock mwinrock at frontiernet.net
Sat Apr 2 18:28:17 EST 2005


max(01)* wrote:
> hi.
> 
> is there a way to define a class method which prints the instance name?
> 
> e.g.:
> 
>  >>> class class_1:
> ...   def myName(self):
> ...     ????what should i do here????
> ...
>  >>> instance_1 = class_1()
>  >>> instance_1.myName()
> 'instance_1'
>  >>>
> 
> bye
> 
> macs

macs,

The object instance doesn't know about the identifier to which you 
assigned it (but see my example below using the inspect module).

If you are just trying to identify different instances, you can get a 
unique instance identifier from hash() function
	hash(instance1)

or
	self.__hash__(), or hash(self) from within the object

The default __str__ for a class will normally return something similar 
with more information , so that when you
	print instance_1
you get a string in the following format:
	<module.classname object at hashvalue>


The following is a very, very, very weak example of how you might use 
inspect to get the information you want. This is not a robust example at 
all, and I imagine it could have many ways it will fail. The init uses 
inspect information to dip into the source file and parse out the info 
-- like I said, this is not a robust parse.
# ------------------------
import os,sys

class class_1(object):
     def __init__(self):
         import inspect
         self.lineno = inspect.currentframe().f_back.f_lineno
         self.filename = inspect.currentframe().f_back.f_code.co_filename
         self.initial_instance = None

         try:
             # i'm not sure if filename is full path or not at this time
             f=open(self.filename,'r')
             lines=f.readlines()
             s = lines[self.lineno-1]
             split = s.split()
             try:
                 # find the assignment if possible
                 i = split.index('=')
                 self.initial_instance = split[i-1]
             except ValueError:
                 pass
         finally:
             f.close()

     def myName(self):
         print 'my initial instance was \'%s\''%(self.initial_instance)

if __name__ == '__main__':

     # two straight up examples
     instance_1 = class_1()
     instance_2 = class_1()

     instance_1.myName()
     instance_2.myName()

     #
     class_1().myName()

     c = instance_1

     c.myName()
# -----------------------------------------------

I got the following results:
my initial instance was 'instance_1'
my initial instance was 'instance_2'
my initial instance was 'None'
my initial instance was 'instance_1'



Best-regards,
Mark



More information about the Python-list mailing list