01, application scenario and definition mode application scenario
- In real-world development, some properties or methods of an object may only want to be used inside an object and not be externally accessible to
- A private property is a property that an object does not want to expose
- Private Methods are methods that objects do not want to expose
How to define
- when defining a property or method , add an underscore before the property name or method name , defined as a private property or method
class Women: def __init__(self, name): self.name = name self.__age = 18 # def __secret(self): def secret(self): # 在对象的方法内部,是可以访问对象的私有属性的 print("%s 的年龄是 %d" % (self.name, self.__age)) namei = Women("娜美") # 私有属性和私有方法,在外界不能直接别访问 # namei.__age() # namei.__secret() namei.secret() # 结果呈现 娜美 的年龄是 18
02, pseudo-private properties and private methods
tip : In daily development, do not use this method to access the object's private properties or private methods
python
In, and there is no real sense of private
- In the name of the property, the method is actually a number of special processing, so that the outside world can not access the
- How to handle : Add the name in front of
__类名
__类名__名称
class Women(): def __init__(self, name): self.name = name self.__age = 18 def __secret(self): # def secret(self): # 在对象的方法内部,是可以访问对象的私有属性的 print("%s 的年龄是 %d" % (self.name, self.__age)) namei = Women("娜美") # 私有属性和私有方法,在外界不能直接别访问 # namei.__age() namei._Women__secret() # namei.secret() # 结果呈现 娜美 的年龄是 18
Python Object-oriented---private properties and private methods