[Tutor] Strange list behaviour in classes

Lie Ryan lie.1296 at gmail.com
Wed Feb 24 04:27:26 CET 2010


On 02/24/10 10:27, C M Caine wrote:
> Thanks all (again). I've read the classes tutorial in its entirety
> now, the problem I had didn't seem to have been mentioned at any point
> explicitly. I'm still a fairly inexperienced programmer, however, so
> maybe I missed something in there or maybe this is a standard
> procedure in other OO programming languages.

Not exactly, staticcally-typed languages typically uses keywords (like
"static") to declare an variable as a class variable; but since in
python, you don't need to do variable declaration the chosen design is
to define class variable in the class itself and instance variable
inside __init__() [actually this is not a precise description of what's
actually happening, but it'll suffice for newbies]

class MyClass(object):
    classvariable = 'classvar'
    def __init__(self):
        self.instancevariable = 'instvar'

if you want to access class attribute from inside a method, you prefix
the attribute's name with the class' name, and if you want to access
instance attribute from inside a method, prefix with self:

class MyClass(object):
    classvariable = 'classvar'
    def __init__(self):
        self.instancevariable = 'instvar'
    def method(self):
        print MyClass.classvariable
        print self.instancevariable


But due to attribute name resolution rule, you can also access a class
variable from self:

class MyClass(object):
    classvariable = 'classvar'
    def __init__(self):
        self.instancevariable = 'instvar'
    def method(self):
        print self.classvariable


as long as the class variable isn't shadowed by an instance variable

class MyClass(object):
    var = 'classvar'
    def method(self):
        print self.var    #'classvar'
        self.var = 'instvar'
        print self.var    #'instvar'
        del self.var
        print self.var    #'classvar'




More information about the Tutor mailing list