2015-10-14 52 views
0

我有一个子类,可能有一个方法'method_x'定义。我想知道'method_x'是否在类层次结构的其他位置定义。如何测试python类的父类是否定义了方法?

如果我做的:

hasattr(self, 'method_x') 

我会得到一个真值也着眼于为子类中定义的任何方法。我怎么限制这个只是询问这个方法是否被定义在类链上?

回答

2

如果您使用Python 3,则可以将super()提供给hasattr的对象参数。

例如:

class TestBase: 
    def __init__(self): 
     self.foo = 1 

    def foo_printer(self): 
     print(self.foo) 


class TestChild(TestBase): 
    def __init__(self): 
     super().__init__() 
     print(hasattr(super(), 'foo_printer')) 

test = TestChild() 

使用Python 2,这是类似的,你只需要在你的super()通话更加明确。

class TestBase(object): 
    def __init__(self): 
     self.foo = 1 

    def foo_printer(self): 
     print(self.foo) 


class TestChild(TestBase): 
    def __init__(self): 
     super(TestChild, self).__init__() 
     print(hasattr(super(TestChild, self), 'foo_printer')) 


test = TestChild() 

2和3都将使用多级继承和mixin。

相关问题