Python 私有变量的应用

Python 中私有变量的采用 __变量名 定义变量,作用范围仅限于本类,可采用以下方式操作:(以下代码采用 python3 验证)

  • 改变或获取私有变量的值
class Test(object):
    def __init__(self):
        self.__num = 100

    def setNum(self, newNum):
        self.__num = newNum

    def getNum(self):
        return self.__num

test = Test()

# 调用setter方法
test.setNum(200)

# 调用getter方法
print("运行结果:", test.getNum())
  • 添加 property 属性

class Test(object):
    def __init__(self):
        self.__num = 100

    def setNum(self, newNum):
        self.__num = newNum

    def getNum(self):
        return self.__num

    num = property(getNum, setNum) # 添加 property

test = Test()

# 调用setter方法
test.num = 200  # 相当于调用了,test.setNum(200)

# 调用getter方法
print("运行结果:", test.num)    # 相当于调用了,test.getNum()

注:
若将 num = property(getNum, setNum) 中 getNum, setNum 交换位置 num = property(setNum, getNum) 会报如下错误:

Traceback (most recent call last):
  File "/Users/youmy/PycharmProjects/Learn/setget.py", line 17, in 
    test.num = 200
TypeError: getNum() takes 1 positional argument but 2 were given

Process finished with exit code 1
  • 使用 装饰器
class Test(object):
    def __init__(self):
        self.__num = 100

    @property
    def num(self):
        return self.__num

    @num.setter
    def num(self, newNume):
        self.__num = newNume

test = Test()

# 调用setter方法
test.num = 200  # 相当于调用了,test.setNum(200)

# 调用getter方法
print("运行结果:", test.num)    # 相当于调用了,test.getNum()

你可能感兴趣的:(Python 私有变量的应用)