Data encapsulation and private attributes
Like java
in the general use private
and protected
to implement private methods and protected methods in the class.
I have chapter04
written a class_method.py
file in the folder, and a Date
class is defined in the file . Date
See this blog for specific classes
Then we import the Date
class
from chapter04.class_method import Date
class User:
def __init__(self):
self.brithday = birthday
def get_age(self):
#返回年龄
return 2018 - self.birthday.year
if __name__ = "__main__":
user = User(Date(1990,2,1))
print(user.get_age()) # 28 2018-1990
print(user.birthday) # 1990/2/1 可以获取到用户的birthday
User
The parameter passed in the initialization of the class is a date of birth, but if we want to hide the object when getting someone's age birthday
, that is , it cannot be directly accessed birthday
, hide it.
python
Use double underline to encapsulate private attributes.
class User:
def __init__(self):
self.__brithday = birthday
def get_age(self):
#返回年龄
return 2018 - self.__birthday.year
if __name__ = "__main__":
user = User(Date(1990,2,1))
print(user.get_age()) # 28
print(user.__birthday) # ‘User’ object has no attribute ‘__birthday’
Private properties cannot be obtained through 实例.私有属性
or through subclasses, but they can still be used in public methods in the class, that is, the print(user.get_age())
result is 28.
Adding a double underscore in front of a function can also hide the function, but in theory, the double underscore does not solve the absolute privacy of private properties from the language level, but adds a little trick. Will __birthday
become _User__birthday
such a structured method.
_User__birthday
Which User
represents the current class, if it is another class, change to another class name, which can also alleviate the conflict of the same attribute name between different classes.
print(user._User__birthday) # 1990/2/1
#这样就能访问到了