[Tutor] question about classes and atributes

Alan Gauld alan.gauld at btinternet.com
Fri Nov 3 18:18:26 CET 2006


"euoar" <euoar at yahoo.es> wrote in 
> Thank you for your answer and the examples. 
> So without self it is an instance variable (like "static" 
> in java/c#). 

Without self it is a class attribute like static etc in C++/Java.
An instance variable is one that is unique to an instance!

Although I think it may be more powerful since I seem to 
recall that static members are not accessible via inheritance
whereas Python class variables are. Also i'm not sure if 
statics can be reached via an instance whereas Python class 
variables can.

But my Java/C# is very rusty on statics...

Note also that you can go even further by specifying 
class methods too but they need special syntax. 

If you are only familiar with Java style statics you might 
find the concept of class variables and methods a little 
different in Python, which follows the traditional OOP 
style of Lisp and SmallTalk rather than the hybrid OOP 
style of Java etc. That is, a class variable/method is 
usually treated as one that applies to the class itself, 
or one that is shared by all instances. Java tend to use 
static methods as a replacement for traditional functions, 
ie. things you can do without creating an instance. You can 
do both things in any of the languages but conceptually 
they tend to be treated differently, especially since 
Python supports stand-alone functions.

> Are you creating new atributes and methods at run time? 
> Is that what has happened? In fact I have tried also this:

Yes, Python classes are a special type of container (really 
a special type of dictionary) , so just as you can add new 
keys to a dictionary you an add new attributes to a class
or object at run time.

> So, in python, you can add methods at run time to an 
> object, and even you can add them to a class at run time?

I'm not sure about adding methods at run time, I've never 
tried it but I think the magic around the self parameter 
might not work. But you can definitely add attributes.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list