Python父类对子私有变量的访问 [英] Python parent class access to child private variables

查看:413
本文介绍了Python父类对子私有变量的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码会产生错误:

class A(object):
    def say_something(self):
        print(self.foo)
        print(self.__bar)

class B(A):
    def __init__(self):
        self.foo = 'hello'
        self.__bar = 'world'

test = B()
test.say_something()

"hello"的打印成功,但是"world"会产生以下错误:

Printing of 'hello' is successful but 'world' generates the following error:

    print(self.__bar)

AttributeError:"B"对象没有属性"_A__bar"

AttributeError: 'B' object has no attribute '_A__bar'

对此我感到很惊讶,我希望我的父类拥有一个可以访问其子级保证具有的私有属性的方法.有解决这个问题的标准方法吗?

I am surprised by this, I would like my parent class to have a method which has access to a private attribute its children are guaranteed to have. Is there some standard way of solving this problem?

推荐答案

您可以使用self._B__something进行访问.但是,这不是yuo应该做的.正确的解决方案是将__bar重命名为_bar.

You can use self._B__something to access it. However, this is not what yuo should do. The proper solution is renaming __bar to _bar.

双下划线名称背后的想法修改是为了避免与子类/超类发生冲突-并不是要用于私有变量.如果应将变量视为私有/内部变量,请在变量前加上一个下划线.这不会引起任何特殊处理,但是每个python开发人员都会知道,它不属于包含该变量的类/模块的公共API的一部分.

The idea behind the double-underscore name mangling is to avoid conflicts with subclasses/superclasses - it's not meant to be used for private variables. If a variable should be considered private/internal, prefix it with a single underscore. This does not cause any special treatment but every python developer will know that it's not part of the public API of the class/module containing that variable.

这篇关于Python父类对子私有变量的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆