[Tutor] Re: What self is this ?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 23 19:34:34 CEST 2004


> > For example
> >
> > class XZY:
> > 	def __init__(self):
> > 		self.instenceName = ????
> >
> > 	def who(self):
> > 		Print self.instenceName
> >
> >
> > test1 = XZY()
> >
> > I want test1.who() to print test1
>
> ok, how about:
>
>    test2 = test1 = XZY()
>
> After that, test2 is test1 (the names 'test1' and 'test2' refer to the
> same object, to see that try 'print test1' you will get something like
> <__main__.XYZ instance at 0x40517b0c> that octal number will be the same
> for test1 and test2), would test1.who() print test1 or test2?


Hi John,

Abel is showing that asking Python to try to infer the name of the
instance is ambiguous, since an instance can go by several variable names.


Rather than force Python to infer it, would it be ok if you explicitely
give your instance a name?  For example:

###
class XZY:
    def __init__(self, name):
        self.name = name
    def who(self):
        print self.name

test1 = XYZ('test1')
test2 = XYZ('test2')
test3 = XYZ('test3')
###


There's some repetition here.  We can fix this by storing the testX names
in a dictionary:

###
tests = []
for name in ['test1', 'test2', 'test3']:
    tests[name] = XYZ(name)
###


> > 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.

If you're iterating across a collection of classes, to make a bunch of
instances, then you may want the instances themselves to be collected
somewhere, like a dictionary.  It may make it easier to manage them, since
you can do mass-actions on them, like passing them all off of a function
at once.


Hope this helps!



More information about the Tutor mailing list