Data encapsulation and private attributes in Python

Data encapsulation and private attributes

Like javain the general use privateand protectedto implement private methods and protected methods in the class.

I have chapter04written a class_method.pyfile in the folder, and a Dateclass is defined in the file . DateSee this blog for specific classes

Then we import the Dateclass

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   

UserThe 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.

pythonUse 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 __birthdaybecome _User__birthdaysuch a structured method.

_User__birthdayWhich Userrepresents 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
#这样就能访问到了

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106916385