python - 获取方法/函数中使用的类的列表

标签 python python-3.x

我正在尝试基于另一个类的方法内部使用的类构建依赖关系树。所以不是父类。为此,我想检查方法是否使用任何继承自名为 Table 的特殊类的类。

示例:

class TestTableOne(Table):
    """Class for testing table loader"""
    def source(self):
        source_file = os.path.join('data',
                                   'test_table_one.csv')
        return pd.read_csv(source_file, dtype=dtype, converters=converters)

    def output(self):
        output_path = 'out/path'
        return output_path

    def post_processors(self):
        return [
            drop_age_column,
            calculate_new_age
        ]

class TestTableTwo(Table):
    """Class for testing tables loader"""
    def source(self):
        return TestTableOne.fetch()

    def output(self):
        output_path = os.path.join(tempfile.mkdtemp(),
                                   'output',
                                   self.get_cached_filename('test_table_one', 'pkl')
                                  )
        return output_path

    def something_does_nothing(self, table):
        result = TestTableOne.get()
        return result

    def post_processors(self):
        return [
            self.something_does_nothing
        ]

在这里,我希望能够检查 TestTableTwo.source 是否依赖于继承自 Table 的任何其他类,在本例中为 TestTableOne >.

所以我想问类似于inspect.classes_that_appears_in(TestTableTwo.source)的问题并得到[TestTableOne]

这在Python中可能吗?顺便说一句,我使用的是 python 3。

最佳答案

这是一个令人讨厌的建议,但你可以尝试一下:

使用inspect.getsource,您可以获得给定对象的源代码,并且您 可以根据您的需要解析原始文本。

import inspect

class Table(object):
    pass

class TestTableOne(Table):
    """Class for testing table loader"""
    def source(self):
        return None

class TestTableTwo(Table):
    """Class for testing tables loader"""
    def source(self):
        return TestTableOne.source()

print(inspect.getsource(TestTableTwo.source))
print(TestTableOne.__name__ in inspect.getsource(TestTableTwo.source))

这将输出:

    def source(self):
        return TestTableOne.source()

True

我注意到您仍然需要一些工作来完善此方法以满足您的要求。

关于python - 获取方法/函数中使用的类的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45413235/

相关文章:

django - 如何正确结合 Django-Allauth 和自定义用户配置文件应用程序?

带有可变参数的 Python "maximum recursion depth exceeded in comparison"。但是,可以很好地处理列表

python - 当用户导入已弃用的变量时引发自定义 ImportError

python - 有没有办法让这段代码在计算机上的负担更少?

python - "CSV file does not exist"用于带有嵌入引号的文件名

python - 检测列表中的相同值

linux - 在 Python3 中使用 HTMLParser 解析 HTML

python - 近似平方根的牛顿法

python - 切掉一个角的矩形的非精确形状检测

python - 类装饰器上的 Mypy 注释