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

时间:2017-07-31 10:21:38

标签: 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 btw。

2 个答案:

答案 0 :(得分:2)

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

使用class BasicStatusTile : StackPanel { private TextBlock TopText { get; set; } private TextBlock BottomText { get; set; } public BasicStatusTile() { InitializeComponent(); } private void InitializeComponent() { TopText = new TextBlock() { Text = "0", HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch, TextAlignment = Windows.UI.Xaml.TextAlignment.Center, FontSize = 48 }; BottomText = new TextBlock() { Text = "Speed (km/h)", HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch, VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Bottom, TextAlignment = Windows.UI.Xaml.TextAlignment.Center }; base.Children.Insert(0, TopText); base.Children.Insert(1, BottomText); base.Background = new SolidColorBrush(Colors.White); base.SizeChanged += BasicStatusTile_SizeChanged; } private void BasicStatusTile_SizeChanged(object sender, Windows.UI.Xaml.SizeChangedEventArgs e) { double third = base.ActualHeight / 6; TopText.FontSize = third * 4; BottomText.FontSize = third; } } ,您可以获得给定对象的源代码 可以根据您的需要解析原始文本。

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))

我注意到您仍需要一些工作来改进这种方法以满足您的要求。

答案 1 :(得分:1)

以下是使用inspect__mro__的示例:

class Table:
    var = "hello"
    def source(self):
        return self.var

class A(Table):
    def source(self):
        return Table.source()

class B(A):
    def source(self):
        return A.source()

class C(B):
    def source(self):
        return B.source()

def check(cls):
    import inspect
    func_name = inspect.getsourcelines(cls)[0][1].lstrip().strip('\n').split('return')[1].split('.')[0]
    func_name_inherits = [k.__name__ for k in eval(func_name + '.__mro__')]
    if 'Table' in func_name_inherits:
        return True
    else:
        return False

if __name__== '__main__':
    print('The return of C.source() inherits from Table:', check(C.source))
    print('The return of B.source() inherits from Table:', check(B.source))
    print('The return of A.source() inherits from Table:', check(A.source))

输出:

The return of C.source() inherits from Table: True
The return of B.source() inherits from Table: True
The return of A.source() inherits from Table: True