简体   繁体   中英

prioritized decorator for instantiating instance of class

Hi this is newbie in python, I want write a prioritized decorator which will decide which class instance has to be instantiated depending upon the priority value passed to the decorator.

# abstract class
class Base:
   def method1(self):
    pass

@deco(priority=1)
class A(Base):
    def method1(self):
        pass

@deco(priority=3)
class B(Base):
    def method1(self):
        pass

@deco(priority=2)
class C(B):
    def method1(self):
        pass

def return_class_obj():
# this method will return the object based upon the priority of the 
# class passed through decorator

It seems that you need something like this:

class Factory():
    registred = {}

    @classmethod
    def register(cls, priority):
        registred = cls.registred
        def inner(inner_cls):
            registred[priority] = inner_cls
            return inner_cls
        return inner
    @classmethod
    def get(cls):
        return min(cls.registred.items())[1]()

@Factory.register(3) 
class A():
    def test(self):
        print "A"

Factory.get().test()

@Factory.register(2)
class B():
    def test(self):
        print "B"

Factory.get().test()

@Factory.register(1)
class C(B):
    def test(self):
        print "C"

Factory.get().test()

This will output ABC

Here is a working implementation of deco and return_class_obj . The decorator installs the prioritized subclasses in a Base attribute, which return_class_obj looks up.

def deco(priority):
    def _deco(cls):
       cls._cls_priority = priority
       if not hasattr(Base, '_subclasses'):
          Base._subclasses = {}
       Base._subclasses[priority] = cls
       return cls
    return _deco

def return_class_obj():
    # return Base subclass with the highest priority
    return Base._subclasses[max(Base._subclasses)]

When using the decorator, don't forget to add the @ before the decorator invocation, otherwise the decorator will be a no-op.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM