如何“隐藏”子类中的超类方法
我基本上想创建一个子类,“隐藏”超类上的方法,以便它们不会出现在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
分别重写 __dir__ 和 __getattribute__ 方法应该可以解决问题。这几乎是在 Python 中执行此类操作的规范方法。尽管您是否应该真正这样做完全是另一回事。
请参阅有关自定义属性访问的 Python 文档
使用
__dir__
列出可用属性(这不会影响实际属性访问)使用
__getattribute__
控制实际属性访问这可能就是您想要的正在努力做。
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)Use
__getattribute__
to control actual attribute accessThis is probably what you are trying to do.
那么你不应该继承子类,你应该使用组合。将其他类实例包装在新的类实例中并根据需要使用。
You should not subclass then, you should use composition. Wrap your other class instance in a new class instance and use as necessary.