[Tutor] Populating a list with object to be called by a class

Steven D'Aprano steve at pearwood.info
Thu Sep 20 21:39:44 CEST 2012


On 21/09/12 02:57, eryksun wrote:
> On Thu, Sep 20, 2012 at 12:25 PM, eryksun<eryksun at gmail.com>  wrote:
>>
>>              cls._count += 1
>
> I forgot the obligatory warning about class variables.

Python is not Java. In Python, classes are first-class objects (no pun
intended) and can be assigned to variables the same as any other type.

x = something_that_returns_a_float()  # x is a float variable
s = something_that_returns_a_string()  # s is a string variable
C = something_that_returns_a_class()  # C is a class variable

Preferred terminology is attribute, not variable. Class attributes live
in the class and are shared across all instances. Instance attributes
live in the instance and are not shared.


> The subclass gets a shallow copy of the parent class namespace.

Not so much.

py> class C(object):
...     x = 1
...
py> class D(C): pass
...
py> D.__dict__ == C.__dict__
False
py> 'x' in D.__dict__
False




-- 
Steven


More information about the Tutor mailing list