Hidden attribute assignment and value in Python class

1. Hidden attribute assignment and value in Python class

The following methods are used to assign values ​​to hidden attributes through the Set and Get methods

#coding=utf-8
# 学习访问限制
class Person():
    def __init__(self,age,name,money):
        self.__age__ = age
        self._name = name
        # 如果要让内部属性不被外部直接访问,在属性前加两个下划线,这个属性变为私有属性,只能在类内部访问
        self.__money = money
    def SetMoney(self,money):
        if money > 0:
            self.__money = money
    def GetMoney(self):
        return self.__money
# 隐藏属性money只能通过实例的初始化赋值一次
PersonObj = Person("jack",18,10000)
#print(PersonObj.__money)  # 直接通过实例.属性名访问会报错

# 通过 SetMoney,GetMoney 方法可以对隐藏属性money进行赋值与取值
PersonObj.SetMoney(2000)
print(PersonObj.GetMoney())

# 不能直接访问PersonObj.__money 是因为Python解释器把 __money 变成了 _Person__moeny,仍然可以用_Person__money 去访问
print(PersonObj._Person__money)

# 在Python中,__XXX__ 属于特殊变量,可以直接访问
print(PersonObj.__age__)

# 在Python中,_XXX__ 变量,这样的实例变量外部是可以访问的,但是按照规则,当看到这样的变量时,意思是“虽然我可以被访问,但我是私有变量,不要直接访问”
print(PersonObj._name)

Second, the second method hides the assignment and value of attributes

This looks like it’s assigning and fetching values ​​to attributes, but it’s actually called the Age method, and when assigning values, it can also judge whether the data meets the requirements, and assign values ​​if it meets the requirements, otherwise the assignment will fail.

class Person2():
    def __init__(self,Age):
        self.__Age = Age
    @property
    # 方法名为受限制的变量去掉双下划线
    def Age(self):
        return self.__Age
    # 方法名.setter
    @Age.setter
    def Age(self,Age):
        if Age > 0:
            self.__Age = Age

Person2Obj = Person2(18)
Person2Obj.Age = 20
print(Person2Obj.Age)

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/110196428