1

I came across this question in one of the quizzes, and did not understand the reason behind printing 'BMW' as an output. The company names in both classes are private, so why one could be accessed and the other one could not. Can someone please explain the logic behind the overall output.

class Bike:
    
    def __init__(self):
        self.__Company_name = "BMW"
        self.price = 2000
        
    def details(self):
        print('Name: ',self.__Company_name,'   Price: ',self.price)


class Car(Bike):
    
    def __init__(self):
        super().__init__()
        self.__Company_name = "Audi"
        self.price = 4000
            
            
obj = Car()
obj.details()

Output:

Name:  BMW    Price:  4000
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Soly
  • 155
  • 1
  • 2
  • 9
  • Because, you are using double-underscore name-mangling, so in `Bike.details` you use `self. _Bike__Company_name`... that's the *whole point* of double-underscore name-mangling, to prevent name collisions in the subclss – juanpa.arrivillaga Dec 21 '20 at 18:24

0 Answers0