0

嗨,这是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
4

2 回答 2

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

于 2012-10-28T08:12:19.227 回答
0

这是decoand的工作实现return_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)]

使用装饰器时,别忘了@在装饰器调用前加上,否则装饰器将是空操作。

于 2012-10-28T07:52:57.223 回答