繁体   English   中英

如何测试python类父是否定义了方法?

[英]How to test if python class parent has method defined?

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

如果我做:

hasattr(self, 'method_x')

我将得到一个真值,它也会查看为子类定义的任何方法。 我如何限制这个只是询问该方法是否被定义在类链的更高位置?

如果您使用的是Python 3,则可以将super()hasattr的object参数。

例如:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM