[英]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. 嗨,这是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
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
这将输出
ABC
Here is a working implementation of deco
and return_class_obj
. 这是
deco
和return_class_obj
的有效实现。 The decorator installs the prioritized subclasses in a Base
attribute, which return_class_obj
looks up. 装饰器将优先级子类安装在
Base
属性中,该属性return_class_obj
查找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)]
When using the decorator, don't forget to add the @
before the decorator invocation, otherwise the decorator will be a no-op. 使用装饰器时,请不要忘记在装饰器调用之前添加
@
,否则装饰器将是空操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.