代码之家  ›  专栏  ›  技术社区  ›  cmcginty

Python中私有名称损坏的好处是什么?

  •  12
  • cmcginty  · 技术社区  · 15 年前

    private name mangling 类方法和属性。

    是否有任何需要这个特性的具体案例,或者只是java和C++的一个继承?

    我只是想防止作者无意中接触到外因。我认为这个用例与Python编程模型不一致。

    4 回复  |  直到 15 年前
        1
  •  25
  •   RichieHindle    15 年前

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

    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
    

    如果没有私人名字的损坏,我偶然重复使用你的名字会破坏你的图书馆。

        2
  •  15
  •   too much php    15 年前

    PEP 8 :

    如果子类无意中包含同名属性,这有助于避免属性名冲突。

    (着重强调)

        3
  •  3
  •   grepit    6 年前

    前面所有的答案都是正确的,但这里有一个例子说明另一个原因。python中需要名称混乱,因为要避免重写属性可能导致的问题。换句话说,为了重写,Python解释器必须能够为子方法和父方法构建不同的id,并使用uuu(双下划线)使Python能够这样做。在下面的示例中,如果没有yu 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")
    
        4
  •  -1
  •   Lennart Regebro    15 年前

    名称混乱是为了防止意外的外部属性访问。主要是为了确保没有名字冲突。