如何“隐藏”子类中的超类方法

发布于 2024-11-03 16:40:04 字数 136 浏览 4 评论 0原文

我基本上想创建一个子类,“隐藏”超类上的方法,以便它们不会出现在 dir()hasattr() 调用和用户中无法打电话给他们(至少不能通过任何正常渠道)。我也想用尽可能少的“魔法”来做到这一点。谢谢。

I basically want to create a subclass that "hides" methods on the superclass so that they don't show up in a dir() or hasattr() call and the users can't call them (at least not through any of the normal channels). I would also like to do this with the least amount of "magic" possible. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不醒的梦 2024-11-10 16:40:04

分别重写 __dir__ 和 __getattribute__ 方法应该可以解决问题。这几乎是在 Python 中执行此类操作的规范方法。尽管您是否应该真正这样做完全是另一回事。

请参阅有关自定义属性访问的 Python 文档

使用 __dir__ 列出可用属性(这不会影响实际属性访问)

class A(object):
    def __dir__(self):
        return []

>>> print dir(A())
[]

使用 __getattribute__ 控制实际属性访问

class A(object):
    def __getattribute__(self, attr):
        """Prevent 'private' attribute access"""
        if attr.startswith('_'):
            raise AttributeError

        return object.__getattribute__(self, attr)


>>> a = A()
>>> a.x = 5
>>> a.x
5
>>> a._x = 3
>>> a._x
AttributeError

这可能就是您想要的正在努力做。

class NoSuper(object):
    def __getattribute__(self, attr):
        """Prevent accessing inherited attributes"""
        for base in self.__bases__:
            if hasattr(base, attr):
                raise AttributeError

        return object.__getattribute__(self, attr)

Overriding the __dir__ and __getattribute__ method respectively should do the trick. This is the pretty much the canonical way to do this kind of stuff in Python. Although whether you should be actually doing this is entirely a different matter.

See Python docs on Customizing Attribute Access

Use __dir__ to list available attributes (this won't affect actual attribute access)

class A(object):
    def __dir__(self):
        return []

>>> print dir(A())
[]

Use __getattribute__ to control actual attribute access

class A(object):
    def __getattribute__(self, attr):
        """Prevent 'private' attribute access"""
        if attr.startswith('_'):
            raise AttributeError

        return object.__getattribute__(self, attr)


>>> a = A()
>>> a.x = 5
>>> a.x
5
>>> a._x = 3
>>> a._x
AttributeError

This is probably what you are trying to do.

class NoSuper(object):
    def __getattribute__(self, attr):
        """Prevent accessing inherited attributes"""
        for base in self.__bases__:
            if hasattr(base, attr):
                raise AttributeError

        return object.__getattribute__(self, attr)
掌心的温暖 2024-11-10 16:40:04

那么你不应该继承子类,你应该使用组合。将其他类实例包装在新的类实例中并根据需要使用。

You should not subclass then, you should use composition. Wrap your other class instance in a new class instance and use as necessary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文