What's the difference between getattr(self, '__a') and self.__a in python? -


I thought before I ran this code:

  class B ( Object:): DEF show (self): self .__a = "exam" print "b" dff_b (self): print "this_b" print itself .___ print a getattr (self, '__a') #expression class C (B): DEF SHOW (H): Print "C" #BISHO (HELD) SUPER (C, SELF) Show () Def call (self): print "call" self. Show () self.this_b () # print itself .__aC (). Call ()   

It raises AttributeError: the 'C' object has a attribute '__a' with the getattr statement, but Why?

The reason for this is.

Private name mangling: When an identifier is found in class definition, then two or more than two underscores begin with characters and two or more Underscore does not end in, it is considered a private name for that class. Private names change for a long time before code is ready for them. Transformation involves the name of the class, the leading underscore is removed in front of the name and an underscore is inserted. For example, the identifier in the class named __spam will be converted to _Ham__spam . This change is independent of syndicated context in which the identifier is used. If the converted name is too long (more than 255 characters), then there can be defined defined cuts. If there are only underscores in the name of the class, then there is no change.

/ P>

  print getattr (self, '__a')   

You have to do this manually,

  print getattr ( Self, '_B__a') # Exam    

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -