1

I was trying to understand this example working.

class P: 
   def __init__(self): 
      self.__x=100 
      self.y=200 
   def print(self): 
      print(self.__x, self.y)  
class C(P): 
   def __init__(self):
      super().__init__()  <-------------------
      self.__x=300 
      self.y=400
       
        
d = C() 
d.print()

output: 100 400

class P: 
   def __init__(self): 
      self.__x=100 
      self.y=200 
   def print(self): 
      print(self.__x, self.y)  
class C(P): 
   def __init__(self):      
      self.__x=300 
      self.y=400
      super().__init__()   <--------------------
       
        
d = C() 
d.print()

output: 100 200

Can someone explain the execution flow of the above codes leading to separate outputs?

user3471438
  • 333
  • 1
  • 2
  • 12
  • Does this answer your question? [Python double underscore mangling](https://stackoverflow.com/questions/13498151/python-double-underscore-mangling) – Green Cloak Guy Mar 07 '22 at 16:07
  • @Green-Cloak-Guy -- I am trying to understand how the placement of 'super().__init__()' line affecting the output. – user3471438 Mar 07 '22 at 16:19
  • `self.y` isn't affected by mangling, so whichever sets it last 'wins' and overwrites whatever it was set to first. In your first example that's `C.__init__()`, which sets it to 400, but in your second example it's `P.__init__()`, which sets it to 200. – Green Cloak Guy Mar 07 '22 at 16:21
  • ahh..that clears my confusion! Thank you! – user3471438 Mar 07 '22 at 16:24

0 Answers0