Python private property and private methods

Private property and private methods

01. scenarios and define the way

Scenarios

  • In the actual development, the object  of  some of the properties or methods  may only want to  be used inside the object , while  not wishing to be externally accessible to
  • Private property  is  the object  not want to expose  properties
  • Private method  is  an object  does not wish to disclose the  method

Defined way

  • In  the definition of the properties or methods , the  former property name or method name  to increase  two underscores , is the definition of  private  property or method
Women class: 

    DEF __init __ (Self, name): 

        self.name name = 
        # Do not ask girls ages 
        Self .__ Age = 18 

    DEF __secret (Self): 
        Print ( "my age is d%"% Self .__ Age) 


xiaofang = Women ( "Xiao Fang") 
# private property, can not directly access external 
# Print (xiaofang .__ Age) 

# private methods, external can not directly call 
# xiaofang .__ secret ()

02. The method of pseudo-private attributes and private (science)

Tip: In the daily development, do not use this way , access to the object of private property or private method

Python , There is no  real sense  of  private

  • Giving  properties , methods  naming, is the actual  name  to do some special treatment, so that the outside world can not have access to
  • Treatment : in the  name  preceded  _类名 => _类名__名称
# Private property, can not directly access to external 
Print (xiaofang._Women__age) 

# private methods, external can not directly call 
xiaofang._Women__secret ()

  

Guess you like

Origin www.cnblogs.com/yzg-14/p/12185285.html