This article mainly introduces the implementation method of Python underlying encapsulation. The example code is introduced in detail in this article, which has a certain reference value for your study or work. You can refer to the following for your friends
In fact, the implementation of Python encapsulation features is purely “opportunistic”. The reason why class objects can’t directly call private methods and properties is that Python secretly changed their names during the underlying implementation.
When Python is implemented in the bottom layer, their names are secretly changed to the format of “class name, property (method) name”
class Person: def setname(self, name): if len(name) < 3: Raise valueerror ('name length must be greater than 3! ) self.__name = name def getname(self): return self.__name #Configure setter and getter methods for name name = property(getname, setname) def setage(self, age): if age < 100: self.__age = age else: Raise valueerror ('age must be less than 100! ) def getage(self): return self.__age #Configure getter and setter methods for age age = property(getage, setage) #Define private methods def __display(self): Print (self. Name, "this year", self. Age, "years old. "" xiaobai = Person() xiaobai.name = "xiaobai" xiaobai.age = 20 #Call the hidden display () method directly xiaobai._Person__display()
Xiaobai is 20 years old.
Summary: all properties and methods in Python classes are public. If you want Python to modify the names of class properties or methods in the bottom layer to hide them, you only need to add a double underscore (“\”) before their names.
The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.