Class variables static by default?
lie.1296 at gmail.com
Sun Dec 20 01:44:11 CET 2009
On 12/20/2009 11:10 AM, KarlRixon wrote:
> Given the following script, I'd expect p1.items to just contain
> ["foo"] and p2.items to contain ["bar"] but they both contain ["foo",
> Why is this? Are object variables not specific to their instance?
First of all, dump all the preconception of what 'static' and 'class
variable' means in any previous language you've learned. Those terms is
not the same in python, and not even referring to a similar concept.
In python, 'class variable' is a variable that belongs to a class; not
to the instance and is shared by all instance that belong to the class.
In contrast, 'instance variable' belongs to the instance, and each
instance can make their instance variables refers to different objects
than the other instances.
Note that, in python, an object can be "owned" by multiple variables, or
more precisely "an object can have multiple names".
'static' in python refers to 'staticmethod', these are called
'classmethod' in other languages (C/C++/Java). Python's 'classmethod' is
an entirely different beast than 'classmethod' in other languages.
'staticmethod' in python is a method in a class that is not bound to the
class nor the instance; the class is merely used as organizational tool.
'classmethod' in python is a method that is bound to the class instead
of the instance; the first argument (self/cls) of a 'classmethod' is
bound to the class instead of the instance.
More information about the Python-list