Class variables static by default?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Dec 21 02:33:53 EST 2009


En Sun, 20 Dec 2009 01:16:16 -0300, Steven D'Aprano
<steve at remove-this-cybersource.com.au> escribió:

> On Sun, 20 Dec 2009 11:44:11 +1100, Lie Ryan wrote:
>
>> 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.
>
> Surely, since string variables are strings, and float variables are
> floats, and bool variables are bools, and module variables are modules, a
> class variable will be a class and an instance variable will be an
> instance?
>
>> In contrast, 'instance variable' belongs to the instance, and each
>> instance can make their instance variables refers to different objects
>> than the other instances.
>
> The usual term used in Python is "class attribute" and "instance
> attribute" for the named fields of a class or instance.

I agree with your interpretation of "class variable", but you'll have to
rewrite parts of the official Python documentation so it becomes
consistent with it. The phrase "class variable" appears about 30 times,
always meaning "class attribute"; four of them in the Language Reference,
section "Class definitions", where the OP's issue is discussed:

"Programmer’s note: Variables defined in the class definition are class
variables; they are shared by all instances. To create instance variables,
they can be set in a method with self.name = value. Both class and
instance variables are accessible through the notation “self.name“, and an
instance variable hides a class variable with the same name when accessed
in this way. Class variables can be used as defaults for instance
variables, but using mutable values there can lead to unexpected results.
For new-style classes, descriptors can be used to create instance
variables with different implementation details."

http://docs.python.org/reference/compound_stmts.html#class-definitions

-- 
Gabriel Genellina




More information about the Python-list mailing list