Why does the “name” parameter to __setattr__ include the class, but __getattr__ doesn't?

巧了我就是萌 提交于 2020-01-04 09:03:30

问题


The following code:

class MyClass():
    def test(self):
        self.__x = 0

    def __setattr__(self, name, value):
        print name

    def __getattr__(self, name):
        print name
        raise AttributeError(name)

x = MyClass()
x.test()
x.__y

Outputs:

_MyClass__x
__y
Traceback (most recent call last):
...
AttributeError: __y

The documentation is utterly unhelpful stating the "name" is the "name of the attribute", yet for some reason it's different depending on whether you are setting it or getting it.

What I want to know is:

  • Am I doing something fundamentally wrong here?
  • How do I get x in the first case instead of _MyClass__x?

回答1:


The double underscore invokes name mangling. If you don't need name mangling, don't use double undescore

What is the meaning of a single- and a double-underscore before an object name?

From the Python docs

9.6. Private Variables

“Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.

Notice that code passed to exec, eval() or execfile() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.




回答2:


I'm not sure exactly why this occurs, but if you use _x rather than __x it works as you would expect.



来源:https://stackoverflow.com/questions/2386418/why-does-the-name-parameter-to-setattr-include-the-class-but-getattr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!