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!

wjandrea
  • 28,235
  • 9
  • 60
  • 81
AnnAc0nda
  • 38
  • 6
  • 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. – Silvio Mayolo Oct 01 '22 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? – AnnAc0nda Oct 01 '22 at 17:59
  • @MarcinOrlowski Not – AnnAc0nda Oct 01 '22 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. – Charles Duffy Oct 01 '22 at 18:24

0 Answers0