instance name

Bengt Richter bokr at oz.net
Sat Apr 2 22:20:51 EST 2005


On Sat, 02 Apr 2005 15:48:21 GMT, "max(01)*" <max2 at fisso.casa> 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'
> >>>
>
Names in any given name space do not have a 1:1 relationship with class instances.
If you want to give an instance its own name, give it a name when you create it,
or attach a name to the instance. E.g, maybe this will give you an idea:

 >>> class Ego(object):
 ...     def __init__(self, name='(anonymous)'): self.name = name
 ...     def myName(self): return self.name
 ...
 >>> instance_1 = Ego('one')
 >>> instance_2 = Ego('two')
 >>> instance_1.myName()
 'one'
 >>> instance_2.myName()
 'two'
 >>> instance_2 = instance_1
 >>> instance_2.myName()
 'one'
Did you catch that ;-)

Ok, now without instance name bindings at all, just references from a list:
 >>> egoes = [Ego(name) for name in 'one two three'.split()]
 >>> egoes
 [<__main__.Ego object at 0x02EF1A4C>, <__main__.Ego object at 0x02EF1A6C>, <__main__.Ego object
 at 0x02EF1A8C>]
 >>> for ego in egoes: print ego.myName()
 ...
 one
 two
 three

We don't have to access instance by names like instance_1, if we didn't make
them with bindings like that. E.g., egoes is a name bound to a list of Ego instances,
so we can get at the second (counting from index 0) instance thus, and change it's
name from the outside, since we know it's stored as an attribute called 'name':

 >>> egoes[1].name = 'Zeppo'
 >>> for ego in egoes: print ego.myName()
 ...
 one
 Zeppo
 three 

HTH

Regards,
Bengt Richter



More information about the Python-list mailing list