1

I'm learning Python, I've coded a bit in C++ before. I have simple very code:

class Car:
    def __init__(self, mark):
        self._mark = mark


class Bus:
    def __init__(self):
        self.audi = Car("Audi")

    def display(self):
        print(self.audi._mark)

def main():
    bmw = Car("BMW")
    print(bmw._mark)

    reno = Bus()
    reno.display()

main()

As far as I know in C++, only classes that inherit have access to "protected" attributes. So my questions:

  • What is the purpose of using "protected" attributes / methods in Python?
  • Why do I have access to the attribute _mark from the main function/class Bus?

Thank you for explain!

4
  • 2
    There's no access control happening. All names in Python are public (with a bit of magic changing the name as per the name mangling link above). The _ thing is a convention that Python programmers generally respect, but it's not one that the runtime enforces. Commented Oct 1, 2022 at 17:55
  • so using _ only gives a suggestion to the programmer that the attribute should not be modified outside of the class. And it has no effect on using in code? Commented Oct 1, 2022 at 17:59
  • @MarcinOrlowski Not Commented Oct 1, 2022 at 18:05
  • @AnnAc0nda, right, it's just a convention. It tells the developer they're using an interface that isn't guaranteed to work in the future so their program may break and it'll be their fault. Commented Oct 1, 2022 at 18:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.