Partial 1.0 - Partial classes for Python

Michele Simionato michele.simionato at gmail.com
Thu Feb 8 15:12:07 EST 2007


On Feb 8, 8:15 pm, Thomas Heller <thel... at python.net> wrote:
> I agree with most of the posters is this thread that it is confusing to spread
> the definition of a class over several places or files.
>
> But, there are cases where the trick come in handy - when classes are created
> not by class statements.
>
> In ctypes, for example, a pointer type to a ctypes type is created by calling
> the POINTER function which creates a new class.  When you have done this, the
> usual way to add additional methods to the new class is by assigning them like this:
>
> from ctypes import *
>
> pointer_to_c_int = POINTER(c_int)
>
> @classmethod
> def from_param(cls, value):
>     ... do something ...
>
> pointer_to_c_int.from_param = from_param
>
> IMO, using the tricky class in the recipes mentioned above, you can write instead:
>
> class pointer_to_c_int(partial, POINTER(c_int)):
>     @classmethod
>     def from_param(cls, value):
>         ... do something ...
>
> Thomas

Using a simple decorator like this seeems a better option to me:

def attach_to(cls):
   def attach_method(meth):
      setattr(cls, meth.__name__, meth)
      return meth
   return attach_meth

@attach_to(pointer_to_c)
@classmethod
def from_param(cls, value):
         ... do something ...


 Michele Simionato




More information about the Python-list mailing list