[Tutor] Re: Another aftermath (Stern-Brocot tree):

alan.gauld@bt.com alan.gauld@bt.com
Wed, 9 Jan 2002 15:36:29 -0000


>    class F:
>         def gcd(a,b):
>             # find greatest common divisor of a,b
>         gcd = staticmethod(gcd)
> 
> With instances:
>   >>> a = F(1,2)
>   >>> b = F(2,3)
>   >>> a+b
>   (7/6)
> 
> Without:
>   >>> F.gcd(10,45)
>   5

Which is a good enough demo of how to create and access 
the new static (aka class) methods but is not a good 
example of what a class method should be used for 
- they are normally methods that apply to all instances 
of the class or do things at the abstract class level 
like change the default timeout of a socket class for 
example, or get a list(or count) of all instances... 

Thus a string class method upper() could upper case all 
string instances say. Or a Fraction gcd() class method 
could find the gcd of all existing fraction instances...
Constructors are often implemented as class methods too.

The idea of using static methods to wrap up what should 
really be functions or procedures is a really bad idea 
from Java land IMHO. (Coz Java's broken object system 
offers no other way to do it!)

Bah, humbug :-)

Alan g.