什么是私人的名字在Python重整的好处?(What is the benefit of priva

2019-06-26 11:35发布

Python提供私人名字改编类的方法和属性。

是否有在需要此功能的任何具体案件,或者是它只是一个从Java和C ++结转?

请说明,如果任何一个使用情况下应使用Python的名字改编?

另外,我不感兴趣,在这里笔者只是试图防止意外的外部属性访问的情况。 我相信这个用例不使用Python编程模型保持一致。

Answer 1:

这部分是为了防止意外的内部属性的访问。 下面是一个例子:

在你的代码,这是一个库:

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

没有私人名字改编,我你的名字意外的重用会破坏您的图书馆。



Answer 2:

从PEP 8 :

如果你的类是为了被继承,你有你不想子类使用,可以考虑用双下划线开头命名它们的属性和没有尾随下划线。 这将调用Python的名字改编算法,其中类的名称错位到属性名称。 这有助于避免属性名称冲突应子无意中包含具有相同名称的属性。

(强调)



Answer 3:

所有以前的答案是正确的,但这里是另一个原因,用一个例子。 名称重整是必要的,因为蟒蛇,以避免可能通过重写属性导致的问题。 换句话说,为了覆盖,Python解释器必须能够建立对儿童的方法与父类的方法,并使用__(双下划线)不同的ID使Python来做到这一点。 在下面的例子中,没有__help这个代码是行不通的。

class Parent:
    def __init__(self):
       self.__help("will take child to school")
    def help(self, activities):
        print("parent",activities)

    __help = help   # private copy of original help() method

class Child(Parent):
    def help(self, activities, days):   # notice this has 3 arguments and overrides the Parent.help()
        self.activities = activities
        self.days = days
        print ("child will do",self.activities, self.days)


# the goal was to extend and override the Parent class to list the child activities too
print ("list parent & child responsibilities")
c = Child()
c.help("laundry","Saturdays")


Answer 4:

该名称重整,以防止有意外的外部属性的访问。 大多数情况下,它的存在,以确保没有名称冲突。



文章来源: What is the benefit of private name mangling in Python?