我正在尝试基于另一个类的方法内部使用的类构建依赖关系树。所以不是父类。为此,我想检查方法是否使用任何继承自名为 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/