我有两个文件,judger.py
和judgemethods.py
。
当Judger
中的judger.py
班级正在完成他的工作时,它将通过它具有的判断方法(可能是一个列表)来检查某些规则是否合适。
例如:
在judgemethods.py
中,我编写了一个简单的判断方法,并使用魔术方法将其注册到Judger
@some_magic_method
def better_than_ten(num):
return num > 10
在Judger.py
class Judger:
def __init__(self):
self.methods = []
def judge(self, thing):
for method in self.methods :
if method(thing):
return True
return False
if __name__ == "__main__":
judger = Judger()
# Judge a integer for example
number = 11
judger.judge(number)
我会得到True
。
我想知道如何优雅地实现装饰器或能够自动将函数注册到不同文件中的Judger
对象的东西。
答案 0 :(得分:1)
您实际上不需要在judgemethods.py
中注册judge.py
定义的方法。
事实上似乎没有理智的方法让Judge
知道方法是什么,至少没有导入judgemethods.py
。
如果您对导入内容感到满意,可以使用以下内容:
# In judgemethods.py
# A global list of judge_methods
JUDGE_METHOD_LIST = []
# Your decorator to add stuff to this list
def register_judge_method(f):
JUDGE_METHOD_LIST.append(f)
return f
@ register_judge_method
def some_judging_method():
print 'Judging you'
# In judge.py
import judgemethods as jmYou can always import judgemethods.py
# To access it from within the Judge class
# Add it in your __init__
class Judge(object):
def __init__(self):
self.methods = jm.JUDGE_METHOD_LIST
# ...
def call(self):
for f in jm.JUDGE_METHOD_LIST:
print f
# <function some_judging_method at 0x7f9bacdb46e0>
f()
# 'Judging You'
编辑:OP想要知道他是否必须在他想要使用judgemethods.py
类的每个文件中再次导入Judge
不,这不是必需的。
# main.py
from judge import Judge
j = Judge()
j.call()