A change to a class attribute does not propagate - bug or feature?
John Machin
sjmachin at lexicon.net
Thu Jan 10 07:47:43 EST 2002
vesselin at beonic.com (Vesselin) wrote in message news:<84b16e14.0201092325.242c10df at posting.google.com>...
> """ Please run this code. It seems that in the line:
> def __init__(self, Name = "newClass" + str(baseClass.ClassId)):
> Python takes the value of baseClass.ClassId from somewhere else
> I use ActivePython build 2.1.212
> """
>
> class baseClass:
> ClassId = 1
> def __init__(self, Name):
> baseClass.ClassId += 1
> print "init in baseClass, new ClassId = ", baseClass.ClassId
> self.ClassName = Name
>
> class newClass(baseClass):
> def __init__(self, Name = "newClass" + str(baseClass.ClassId)):
> baseClass.__init__(self, Name)
>
>
Add two print statements, as per following:
class newClass(baseClass):
def __init__(self, Name = "newClass" + str(baseClass.ClassId)):
print "start of init in newClass, Name = %s, " \
"baseClass.ClassId = %s" % (Name, baseClass.ClassId)
baseClass.__init__(self, Name)
print "end of init in newClass, baseClass.ClassId =",
baseClass.ClassId
and run your code again. You will see that the class attribute *is*
being propagated. However the expression for the default value for the
Name arg is evaluated *once*, when the def is compiled -- not each
time that the function is called -- so the default value is frozen at
"newClass1" for ever.
By the way, shouldn't what you are calling ClassName and ClassId in
fact be called InstanceName and InstanceId respectively?
> if __name__ == '__main__':
[snip]
More information about the Python-list
mailing list