Sharing code between instance and class methods

Stefan Schwarzer s.schwarzer at ndh.net
Sun Mar 17 17:01:27 EST 2002


Hello,

I would like to be able to set the same variable for an instance or for
its class. Someting like:

class X:
    def set_in_instance(self, value):
        self.data = value

    def set_in_class(cls, value):
        cls.data = value
    set_in_class = classmethod(set_in_class)

However, if the code to set the value involves several calls of other
methods, the code duplication would become awkward:

class X:
    def set_in_instance(self, value):
        self.meth1(value)
        self.meth2(value)
        x = self.meth3(value)
        self.data = self.meth4(x)

    def set_in_class(cls, value):
        cls.meth1(value)
        cls.meth2(value)
        x = cls.meth3(value)
        cls.data = cls.meth4(x)
    set_in_class = classmethod(set_in_class)

One possibility I can imagine is to put the common code into a static
method:

class X:
    def set_static(obj, value):
        obj.meth1(value)
        obj.meth2(value)
        x = obj.meth3(value)
        obj.data = obj.meth4(x)
    set_static = staticmethod(set_static)

    def set_in_instance(self, value):
        self.set_static(self, value)

    def set_in_class(cls, value):
        cls.set_static(cls, value)
    set_in_class = classmethod(set_in_class)

Is there a more direct way to accomplish the same? (In a concrete case,
the class method should only be in a derived class, and I have a dislike
to modify the base class to support the per-class operation in the
derived class.)

Thanks in advance for your help.

Stefan



More information about the Python-list mailing list