2015-10-14 49 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。

相關問題