我有一个子类,它可能定义了方法“method_x”。我想知道“method_x”是否在类层次结构的其他位置定义。
如果我这样做:
hasattr(self, 'method_x')
我将获得一个真值,该值还查看为子类定义的任何方法。我如何限制它只查询该方法是否在类链的更高层定义?
最佳答案
如果您使用的是 Python 3,则可以向 hasattr
的对象参数提供 super()
。
例如:
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 都可以使用多个级别的继承和 mixins。
关于python - 如何测试python类父类是否定义了方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135268/