简体   繁体   English

Python中的继承和私有属性

[英]Inheritance and Private attributes in Python

class Parent:
    def __init__(self):
        self._lst = []


class Child(Parent):
    def __init__(self):
        super().__init__()

Considering the code above, say I wanted to implement a method in the Child class, am I allowed to used self._lst (which is a private attribute initialized in the Parent Class) for this method?考虑到上面的代码,假设我想在 Child 类中实现一个方法,我是否可以为这个方法使用 self._lst (这是在 Parent 类中初始化的私有属性)? In other words, am I allowed to access private attributes that are initialized in the Parent Class through Subclasses?换句话说,是否允许我通过子类访问在父类中初始化的私有属性?

In python, truly private attributes / methods don't exist .在 python 中,真正的私有属性/方法不存在 There are only naming conventions.只有命名约定。 What this means is if an attribute / method has its name beginning with one underscore, it can still be accessed from anywhere, just like regular attributes / methods.这意味着如果一个属性/方法的名称以一个下划线开头,它仍然可以从任何地方访问,就像常规属性/方法一样。 The only thing that this does is serve as a reminder to yourself and let other developers know that this attribute was not meant to be accessed from the outside.这样做的唯一作用是提醒您自己,并让其他开发人员知道此属性不应从外部访问。

To answer your question, yes, you can use _lst in the function.要回答您的问题,是的,您可以在函数中使用 _lst。 Even in languages that do have real access modifiers, there is frequently a different keyword to distinguish attributes not accessible from anywhere vs those that are not accessible to derived classes.即使在确实有真正的访问修饰符的语言中,也经常有不同的关键字来区分不能从任何地方访问的属性与那些不能被派生类访问的属性。 In python, this is generally signified with a double underscore ( __ ) vs a single underscore ( _ ).在 python 中,这通常用双下划线 ( __ ) 与单下划线 ( _ ) 来表示。 Double underscores are not meant to be accessed from anywhere, while single underscores can be accessed by derived classes.双下划线并不意味着可以从任何地方访问,而单下划线可以由派生类访问。 See here for more information.请参阅此处了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM