用私人成员将类子类化 [英] Subclassing a class with private members

查看:66
本文介绍了用私人成员将类子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于python的真正好处之一就是它可以简单地命名与访问器同名的变量:

One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:

self.__value = 1

def value():
    return self.__value

是否有一种简单的方法可以提供对我希望子类化的类的私有成员的访问权限?通常,我只希望简单地使用类中的原始数据对象,而不必始终使用访问器和变异器。

Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.

我知道这似乎与常规做法背道而驰。私有和公共的想法,但是通常我要作为子类的类是我自己的类之一,我很高兴将成员暴露给子类而不是该类的实例。

I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?

推荐答案

在不进一步破坏封装的情况下不方便。 double-underscore属性通过在要访问的类的前面加上 _ClassName来进行名称修饰。因此,如果您有一个具有 __value属性的 ContainerThing类,则该属性实际上存储为 _ContainerThing__value 。更改类名(或重构分配属性的位置)将意味着破坏所有尝试访问该属性的子类。

Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '_ContainerThing__value'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.

这正是双下划线名称的原因-mangling(不是真正的私有,只是不便)是一个不好的主意。只需使用前划线。每个人都不会碰到您的私人属性,并且您仍然可以在子类和其他方便的情况下访问它。双下划线属性的名称处理仅在避免真正针对特定类的属性发生名称冲突时非常有用,这种情况极为罕见。

This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a single leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.

在记录中,' __ value (和 _value )不同。下划线是名称的一部分。

For the record, '__value' and 'value' (and '_value') are not the same name. The underscores are part of the name.

这篇关于用私人成员将类子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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