本文介绍了Python中私有名称处理的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python为类方法和属性提供了私有名称处理./p>

在某些具体情况下是否需要此功能,或者仅仅是从Java和C ++继承而来?

请描述一个使用案例,其中应该使用Python名称修饰(如果有)?

此外,对于作者只是试图防止意外的外部属性访问的情况,我也不感兴趣.我相信这个用例与Python编程模型不符.

解决方案

部分是为了防止意外的 internal 属性访问.这是一个示例:

在您的代码中,它是一个库:

class YourClass:
    def __init__(self):
        self.__thing = 1           # Your private member, not part of your API

在我的代码中,我将从您的库类中继承

class MyClass(YourClass):
    def __init__(self):
        # ...
        self.__thing = "My thing"  # My private member; the name is a coincidence

如果不更改私人名称,我不小心重用您的名字会破坏您的图书馆.

Python provides private name mangling for class methods and attributes.

Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?

Please describe a use case where Python name mangling should be used, if any?

Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.

解决方案

It's partly to prevent accidental internal attribute access. Here's an example:

In your code, which is a library:

class YourClass:
    def __init__(self):
        self.__thing = 1           # Your private member, not part of your API

In my code, in which I'm inheriting from your library class:

class MyClass(YourClass):
    def __init__(self):
        # ...
        self.__thing = "My thing"  # My private member; the name is a coincidence

Without private name mangling, my accidental reuse of your name would break your library.

这篇关于Python中私有名称处理的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:39