[Tutor] What self is this ?

Chad Crabtree flaxeater at yahoo.com
Thu Sep 23 06:24:23 CEST 2004


Ertl, John wrote:

>I was working on a class and I want to assign the class instance
name (if
>that is the correct term) to an attribute in the class instance.
>
>For example
>
>class XZY:
>	def __init__(self):
>		self.instenceName = ????
>
>	def who(self):
>		Print self.instenceName
>
>
>test1 = XZY()
>
>I want test1.who() to print test1
>
>I know this looks very "Why would you do that?"  but I am trying to
give a
>simple example.  This is coming up in the context of a list of
classes that
>is going to be iterated over.
>
>  
>
Ok.  I'm not really sure about this but here goes. 
#####CODE#####
 >>> class ABC(object):
 >>>    def __init__(self):
 >>>        self.instance=""
  
 >>>a=ABC()
 >>>print globals()
{'a': <__main__.ABC object at 0x01611430>, 'shell':
<wx.py.shell.Shell; 
proxy of C++ wxStyledTextCtrl instance at
_00575601_p_wxStyledTextCtrl>, 
'__builtins__': <module '__builtin__' (built-in)>, '__file__': 
'C:\\Python23\\Scripts\\pyshell', 'ABC': <class '__main__.ABC'>, 
'__name__': '__main__', '__doc__': None}
 >>>type(a)
<class '__main__.ABC'>

 >>>for k,v in globals().items():
 >>>    if type(v)==type(ABC()):
 >>>         v.instance=k
 >>>        print "Intance Name=%s" %k
   
Intance Name=a
#####/CODE#####
Ok.. this session explained.  builtin functions named globals() and 
locals() shows the namespaces represented as python dictionaries. 
Now 
you could look at the globals and locals dictionary (you can assign
to 
them directly also) check for type and then know the variable name
and 
do such.  I don't think this is very sane but perhaps you can do what

you want with this. 

Good Luck



		
_______________________________
Do you Yahoo!?
Declare Yourself - Register online to vote today!
http://vote.yahoo.com


More information about the Tutor mailing list