adding a static class to another class

thebjorn BjornSteinarFjeldPettersen at gmail.com
Mon Sep 17 01:35:10 CEST 2007


On Sep 17, 1:14 am, "Nathan Harmston" <ratchetg... at googlemail.com>
wrote:
> HI,
>
> I m trying to start an api in a similar way to the djangic way of
> Class.objects.all(). Ie objects is a "Manager" class.
>
> So:
>
> class Foo(object):
>    def __init__(self):
>         self.test = "NEE"
>
> class Manager(object):
>     def __init__(self):
>         pass
>    def all(self):
>        return "COCONUTS"
>
> Because of how some of the code is set up I cant use
> metaclasses........so I try to use a decorator:
>
> def addto(instance):
>     def decorator(f):
>         import new
>         f = new.instancemethod(f, instance, instance.__class__)
>         setattr(instance, "objects", f)
>         return f
>     return decorator
>
> class Manager(object):
>     @addto(Foo)
>     def __init__(self):
>        .............
>
> however this only binds the init method to the Foo.objects, so not
> what I want. If I try using classmethod...then it just says the
> Foo.objects doesnt exist.
>
> Does anyone have any ideas how I can accomplish this using decorators?
> And also preventing more than one Manager instance instantiated at one
> time.
>
> Many Thanks in advance,
>
> Nathan

You want to use descriptors (classes that implement __get__, __set__,
__del__). Google for the particulars.

-- bjorn




More information about the Python-list mailing list