adding a static class to another class

Nathan Harmston ratchetgrid at googlemail.com
Sun Sep 16 19:14:37 EDT 2007


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



More information about the Python-list mailing list