如何实现可插入的类并在不同的文件

时间:2016-02-26 12:46:28

标签: python

我有两个文件,judger.pyjudgemethods.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对象的东西。

1 个答案:

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