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

Thomas Heller thomas.heller at ion-tof.com
Mon Jun 18 13:58:39 EDT 2001


> > > 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..
> >
> > No, constructors (at least as available in Python, C++, and Java), are really
> > initialization methods, and thus instance methods. This is easily seen as they
> > get an object as implicit argument.
>
> Yes, I agree that the concrete purpose of constructors is to initialize
> instances. But more generally, and from a semantical point of view, calling a
> constructor *creates* a new instance, even if the programmer gains control only
> on the init part. Then I'd say that a constructor belongs to the class as well as
> to the instance being created.

Much confusion: Maybe we should carefully separate between the _creation_ of
the instance, and _initialization_ of it.
In current Python, the _creation_ is hidden in C, and you cannot override it.
The _initialization_ is exposed as the __init__ method.


The most useful pattern which has emerged from numerous discussions
on the list is to hide the class itself in an instance of another
class. This recipe can be refined, but basically it goes like this:

class ClassMeta:
    class Instance:
        def __init__(self, ...):
            # initialize the new instance
            ....

        def inst_method(self):
            # an instance method

    def new(self, *args):
        # a class method acting as a constructor
        return self.Instance(arg1, arg2):

    def a_class_method(self, ...):
        # another class method
        ....


Class = ClassMeta()

Now you can use it in this way to invoke 'class methods':

Class.a_class_method(spam)

Create an instance:

obj = Class.new(...)

and invoke 'instance methods':

obj.inst_method()

Regards,

Thomas





More information about the Python-list mailing list