[Tutor] class variables

Alan Gauld alan.gauld at btinternet.com
Fri Dec 20 11:20:08 CET 2013


On 20/12/13 07:04, Keith Winston wrote:

> Class.pi == 3.14  # defined/set in the class def
> instance.pi == 3.14  # initially
> instance.pi = 4  # oops, changed it
> Class.pi == 3.14  # still
> Class.pi = "rhubarb"  # oops, there I go again
> instance.pi == 4  # still
>
> Sorry if I'm beating this to a pulp, I think I've got it...

You do have it.

Think of it like an extension to any other form of name look up.
The built in functions are available to you anywhere but you can 
override them in your code. Python  looks first to see if you have 
defined your own version, if you don't it looks in the built in
names.

Similarly if you have a name defined within the instance it will use 
that if not it will look in the class.

My personal rule for this is if you want the class variable always 
access it via the class rather than the instance.

But that falls down when processing a polymorphic collection where some 
instances may have instance variables and others only class variables.
So a loop like this

for obj in myMixedObjectList:
     obj.someName = 42

Those instances that didn't have an instance var called someName
before, have one now. That may not be a good thing, especially
if the objects methods use self.someName to access the class
variable.

But these cases are relatively rare in my experience. Lists of
objects are usually more closely related than in the example above.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list