我想根據運行時提供的標簽名稱運行以下類函式
def tag(tag_name):
def tags_decorator(func):
func._tag = tag_name
return func
return tags_decorator
class ExampleClass:
@tag('foo')
def method_a(self):
print(" method_a foo")
@tag('bar')
def method_b(self):
print(" method_b bar")
def method_c(self):
print(" method_c")
期待:
if __name__ == '__main__':
ec = ExampleClass()
ec.foo # it should run the method tagged with foo i.e. method_a and should
# print " method_a foo"
uj5u.com熱心網友回復:
這似乎是一個奇怪的要求,但您可以實施__getattr__以實作它:
class ExampleClass:
...
def __getattr__(self, name):
for tp in type(self).mro():
for obj in vars(tp).values():
if getattr(obj, '_tag', None) == name:
return obj(self)
raise AttributeError(name)
uj5u.com熱心網友回復:
雖然我同意@a_guest 的觀點,這似乎是一個混亂的代碼設計,但我設法想出了我認為對于實際裝飾器來說是一個不錯的解決方案。
創建一個 Tag 類,該類可以使用標簽的字串進行初始化,并且可以呼叫以回傳一個裝飾器,該裝飾器將標記一個使用用于__init__.
class Tag:
def __init__(self, tag):
self.tag = tag
def __call__(self):
def tag(function):
function.tag = self.tag
return function
return tag
現在奇怪的部分 - 類裝飾器查找所有用標簽標記的方法并將屬性添加到類中,標簽名稱和值是方法。
def TaggedClass(cls):
methods_to_add = []
for method in cls.__dict__.values():
if hasattr(method, "tag"):
methods_to_add.append((method.tag, method))
for tag, method in methods_to_add:
setattr(cls, tag, method)
return cls
將使用標簽的類需要用類裝飾器標記,方法必須用呼叫方法裝飾器標記。
@TaggedClass
class ExampleClass:
@Tag("foo")()
def a_method(self):
print("foo-bar")
if __name__ == '__main__':
ec = ExampleClass()
ec.foo()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/421251.html
標籤:
