2
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? In other words, am I allowed to access private attributes that are initialized in the Parent Class through Subclasses?

11
  • 1
    self._lst (with one underscore) would be accessible from the subclass. self.__lst (with two underscores) would not. Commented Jul 20, 2022 at 3:11
  • 1
    What do you mean by "allowed"? Allowed by whom? The people reviewing your code? Maybe not. Did you try? Commented Jul 20, 2022 at 3:15
  • 2
    @Yaya123 did you try? This seems like something you could have simply discovered yourself in a manner of seconds. As I stated, though, it is a convention. Python doesn't have access modifiers like, say, Java or C++ Commented Jul 20, 2022 at 3:20
  • 2
    Then you really must be clear when you are asking these questions. Fundamentally, this comes down to "whatever the documentation for the class says". Commented Jul 20, 2022 at 3:23
  • 2
    @Yaya123 "Similar to private attributes in public methods" -- Huh? What's wrong with a public method accessing a private attribute? For example, you could have a private attribute with a public getter but no setter. That setup is used all the time with propertys. Commented Jul 20, 2022 at 3:39

1 Answer 1

4

In python, truly private attributes / methods don't exist. 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. 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 anywhere but derived classes. In python, this is generally signified with a double underscore (__) vs a single underscore (_). Double underscores are not meant to be accessed from anywhere, while single underscores can be accessed by derived classes. See here for more information.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.