用于实例化类实例的优先级装饰器

时间:2012-10-28 07:16:48

标签: python decorator

嗨,这是python中的新手,我想编写一个优先级的装饰器,它将根据传递给装饰器的优先级值来决定实例化哪个类实例。

# 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

2 个答案:

答案 0 :(得分:1)

看来你需要这样的东西:

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()

这将输出ABC

答案 1 :(得分:0)

以下是decoreturn_class_obj的有效实施方案。装饰器在Base属性中安装优先级的子类,return_class_obj查找。

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)]

使用装饰器时,不要忘记在装饰器调用之前添加@,否则装饰器将是无操作符。

相关问题