why is there no class (static) methods in Python ?

Richard Gruet rgruet at intraware.com
Sun Jun 17 22:24:43 EDT 2001


Martin,


Martin von Loewis wrote:

> Richard Gruet <rgruet at intraware.com> writes:
>
> > I  (and other people on the Python french mail list) wonder  why there
> > are no class (static) methods in Python. You cannot define a really
> > unbounded (ie to an instance) method within the namespace of a class.
>
> First of all, you *can* define such a thing if you absolutely want, see
>
> http://www.python.org/doc/FAQ.html#4.84
>

Thanx for the info. But the FAQ confirms that there is no way to define easily
a class method. What is recommended (define a module fct) is already what I
use.

> > It's not natural nor elegant to have to create an instance to call a method
> which is not related to a particular instance. We would like to be able to
> write things like:
> >
> > class C:
> >     def staticFoo(x): print x
> >
> > C.staticFoo(1)
>
> I'd like to question why you want to do this. Isn't it much better to write
>
> class C:
>   pass
>
> def staticFoo(x):
>   print x
>
> I.e. what has class C to do with staticFoo?

Of course, my example is fictitious and was only intended to show the desired
syntax. But the reason to choose to define a function as a class method rather
than a mere (static) function is -obviously- when this function is closely
related to the class itself, not to one of its instances. Some languages like
smalltalk even define classes as instances of metaclasses, which makes sense.
Then you can see class methods like methods of instances that are actually
classes.
In fact, constructors (and destructors) are class methods, not instance
methods, but they are handled specially in the language so they appear as
instance methods..

Typical examples of class methods:
loadInstanceFromStream(aStream)    # Create an instance from its persistent
state read on a stream
getInstanceCount()                            # returns the number of instances
of this class
getInstanceList()                                # returns the list of
instances of this class
getClassName()  or getAnyInfoOntheClass() ......


Richard

-------------- next part --------------
A non-text attachment was scrubbed...
Name: rgruet.vcf
Type: text/x-vcard
Size: 370 bytes
Desc: Card for Richard Gruet
URL: <http://mail.python.org/pipermail/python-list/attachments/20010618/b4740cda/attachment.vcf>


More information about the Python-list mailing list