python属性property

1. 私有属性添加getter和setter方法

通过公有方法获取私有属性

class Property(object):
    '''有关property的用法'''
    def __init__(self):
        # 私有属性
        self.__money = 100

    def getMoney(self):
        '''通过公有方法获取私有属性'''
        return self.__money

    def setMoney(self, money):
        '''通过公有方法设置私有属性'''
        self.__money = money
if __name__ == '__main__':
    proper = Property()

    print(proper.getMoney())
    proper.setMoney(200)
    print(proper.getMoney())

运行结果:

/home/longhui/Desktop/core_python_programming/venv/bin/python /home/longhui/Desktop/core_python_programming/venv/include/python_advanced_programming/property_use.py
100
200

Process finished with exit code 0

2. 使用property升级getter和setter方法

class Property(object):
    '''有关property的用法'''
    def __init__(self):
        # 私有属性
        self.__money = 100

    def getMoney(self):
        '''通过公有方法获取私有属性'''
        return self.__money

    def setMoney(self, money):
        '''通过公有方法设置私有属性'''
        self.__money = money

    # 使用property升级getter和setter方法
    money = property(getMoney, setMoney)
if __name__ == '__main__':
    proper = Property()

    # print(proper.getMoney())
    # proper.setMoney(200)
    # print(proper.getMoney())

    # 可以直接通过money获取和设置私有属性
    print(proper.money)
    proper.money = 300
    print(proper.money)

运行结果:

/home/longhui/Desktop/core_python_programming/venv/bin/python /home/longhui/Desktop/core_python_programming/venv/include/python_advanced_programming/property_use.py
100
300

Process finished with exit code 0

3. 使用property取代getter和setter方法

@property成为属性函数,可以对属性赋值时做必要的检查,并保证代码的清晰短小,主要有2个作用

  • 将方法转换为只读
  • 重新实现一个属性的设置和读取方法,可做边界判定
    @property
    def money(self):
        return self.__money

    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print('error:%s不是不是整型数字' % value)
if __name__ == '__main__':
    proper = Property()

    # print(proper.getMoney())
    # proper.setMoney(200)
    # print(proper.getMoney())

    # 可以直接通过money获取和设置私有属性
    # print(proper.money)
    # proper.money = 300
    # print(proper.money)

    print(proper.money)
    proper.money = 400
    print(proper.money)

运行结果:

/home/longhui/Desktop/core_python_programming/venv/bin/python /home/longhui/Desktop/core_python_programming/venv/include/python_advanced_programming/property_use.py
100
400

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_41020281/article/details/80244387