python - 如果传递了类实例,如何执行函数?

标签 python python-3.x callable callable-object

我目前有一个可调用的 TestClass。如果任何属性等于 None,可调用函数将引发异常。将其定义为可调用的目的是当 TestClass 实例被传递给另一个函数或被复制时,它将在传递之前检查所有属性是否存在,否则将引发异常。

下面显示此逻辑的行是 UsesTestClass(testClass())

理想情况下,我希望能够执行相同的检查而不必“调用”类实例。例如,UsesTestClass(testClass)。是否有神奇的方法或其他方法来配置类,使其能够在作为参数传递之前执行函数?

class TestClass:
    def __init__(self):
        self.name = None

    def run(self):
        if self.name is None:
            raise Exception("'name' attribute is 'None'")

    def __call__(self):
        self.run()
        return self

def UsesTestClass(testClass):
    print(testClass.name)

testClass = TestClass()
testClass.name = "Hello"
UsesTestClass(testClass())

最佳答案

如果你使用集成到 python 中的类型库,你可以做到这一点。

import types


class TestClass:
    def __init__(self):
        self.name = None

    def __getattribute__(self, attr):
        method = object.__getattribute__(self, attr)
        if not method:
            raise Exception("Attribute %s not implemented" % attr)
        if type(method) == types.MethodType:
            self.run()
        return method

    def run(self):
        if self.name is None:
            raise Exception("'name' attribute is 'None'")

    def __call__(self):
        self.run()
        return self


def UsesTestClass(testClass):
    print(testClass.name)


testClass = TestClass()
testClass.name = "Hello"
UsesTestClass(testClass)

关于python - 如果传递了类实例,如何执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54953133/

相关文章:

python - 如何在 Apache Spark 中保存和加载 MLLib 模型?

python-3.x - 为什么 PulP 对于混合问题返回负值,而 lowBound 设置为零?

python - 为什么 'module' 对象不可调用?

python - 如何将python元组转换为二维表?

python - Pandas to_hdf 溢出错误

python - MediaWiki API : can it be used to create new articles programatically?

Python 子进程 : Print to stdin, 读取标准输出直到换行,重复

python - 在哪里可以找到 python 的默认抽象类型表?

Java 多线程。如何停止线程并释放启动器?

java - 我们如何将可调用对象转换为可运行对象