[Tutor] the class struggle

Rob McGee i812@iname.com
Fri, 30 Nov 2001 19:19:39 -0600


On Fri, Nov 30, 2001 at 02:22:32PM -0800, Danny Yoo wrote:
> >     How, in a class __init__ function, can you get the name of the
> >     instance?
> 
> 
> This depends on what you mean by "name".  An example might clarify:
> 
> ###
> >>> class Person:
> ...     def __init__(self, name):
> ...         self.name = name
> ...     def sayHello(self):
> ...         print "Hello, my name is", self.name
> [snip]
> Is this what you mean?  What's tricky about your question is the ambiguity
> of the word "name", so if you can give an example, that will help a lot.  
> Hope this helps!

That is exactly what I mean. I simply pass the "name" variable to the
class instantiation. I don't really even need to set a "self.name"
variable -- for my purposes all I need is to evaluate that "name"
parameter inside the __init__ function:

{code}
soviet = ['Lenin', 'Trotsky', 'Stalin']

class Struggle:
  def __init__(self, list, name):
    self.Communist = 1
    if name in list:
      self.Soviet = 1
    else:
      self.Soviet = 0

myList = ['Marx', 'Engels', 'Lenin', 'Mao']

for x in myList:
  execString = x + ' = Struggle(soviet, "' + x + '")'
  exec(execString)
  evalCommunist = x + '.Communist'
  evalSoviet = x + '.Soviet'
  if eval(evalCommunist):
    print x, 'was a known Communist.'
  if eval(evalSoviet):
    print x, 'was a Soviet leader.'

print "rob0 is winning the struggle to understand Python classes."
{/code}

That did it!! Thank you all for turning the light on. :)

    Rob - /dev/rob0