Python name mangling

后端 未结 11 2283
天命终不由人
天命终不由人 2020-11-22 05:31

In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be privat

11条回答
  •  甜味超标
    2020-11-22 06:02

    There are already a lot of good answers to this, but I'm going to offer another one. This is also partially a response to people who keep saying that double underscore isn't private (it really is).

    If you look at Java/C#, both of them have private/protected/public. All of these are compile-time constructs. They are only enforced at the time of compilation. If you were to use reflection in Java/C#, you could easily access private method.

    Now every time you call a function in Python, you are inherently using reflection. These pieces of code are the same in Python.

    lst = []
    lst.append(1)
    getattr(lst, 'append')(1)
    

    The "dot" syntax is only syntactic sugar for the latter piece of code. Mostly because using getattr is already ugly with only one function call. It just gets worse from there.

    So with that, there can't be a Java/C# version of private, as Python doesn't compile the code. Java and C# can't check if a function is private or public at runtime, as that information is gone (and it has no knowledge of where the function is being called from).

    Now with that information, the name mangling of the double underscore makes the most sense for achieving "private-ness". Now when a function is called from the 'self' instance and it notices that it starts with '__', it just performs the name mangling right there. It's just more syntactic sugar. That syntactic sugar allows the equivalent of 'private' in a language that only uses reflection for data member access.

    Disclaimer: I have never heard anybody from the Python development say anything like this. The real reason for the lack of "private" is cultural, but you'll also notice that most scripting/interpreted languages have no private. A strictly enforceable private is not practical at anything except for compile time.

提交回复
热议问题