1

我有一个可能定义了方法“method_x”的子类。我想知道“method_x”是否在类层次结构的其他地方定义。

如果我做:

hasattr(self, 'method_x')

我将得到一个真值,它还查看为子类定义的任何方法。我如何将其限制为仅询问该方法是否在类链的上层定义?

4

1 回答 1

4

如果您使用的是 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 都适用于多层次的继承和混合。

于 2015-10-14T20:48:49.320 回答