Object Orientation: Advanced

First, the class member modifier

  Attributes and methods in a class can be divided into two categories:

      Public members : accessible everywhere, can be inherited

      Private members : cannot be accessed from the outside, and can only be accessed and modified within the class (when modifying and modifying, you can use internal methods to call private properties for external modification), and cannot be inherited.

           Add two __ underscores in front of the definition

class Girl:
    def __init__(self, name, age):
        self.name = name
        self.__age = age
    
    def look_age(self):
        return self.__age

    def modify_age(self):
        self. __age += 1
         return self. __age 

g = Girl( ' li ' , 18 ) # g. __name # Direct error, private member, cannot be directly accessed from outside print (g.look_age()) print (g.modify_age() )

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325107072&siteId=291194637