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

标签 python class hasattr

我有一个子类,它可能定义了方法“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/

相关文章:

python - Python遇到空行如何设置vim不缩进?

从数据表创建 C# 对象

python - 如何防止 hasattr 检索属性值本身

python - 检查相同条件下的多个 hasattr

python - 如何使用结构模式匹配检测可散列类型?

python - python 包装器/包应该安装在哪里

python - 在 python spyne 服务器中打印出整个 SOAP 请求

python - 如何删除某一列每一行中相同的单词?

php - 在函数 PHP 中实例化类是不好的做法吗

java - 你能说对象是对类的引用吗?