首页 python基础教程 Python面向对象-property操作只读属性两种方法详解
pay pay
教程目录

Python面向对象-property操作只读属性两种方法详解

日期: 二月 13, 2023, 11:41 p.m.
栏目: python基础教程
阅读: 423
作者: Python自学网-村长

摘要: 在新式类的使用中property类的使用有很多好处,简化代码,丰富功能等等。property的用法很广泛,可以通过property把函数当做属性使用,方便快捷而且能提前实现数据处理,不像属性那样简单的赋值。

在新式类的使用中property类的使用有很多好处,简化代码,丰富功能等等。property的用法很广泛,可以通过property把函数当做属性使用,方便快捷而且能提前实现数据处理,不像属性那样简单的赋值。

先看文档

"""
Property attribute.

  fget
    function to be used for getting an attribute value
  fset
    function to be used for setting an attribute value
  fdel
    function to be used for del'ing an attribute
  doc
    docstring

Typical use is to define a managed attribute x:

class C(object):
    def getx(self): return self._x
    def setx(self, value): self._x = value
    def delx(self): del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

Decorators make defining new properties or modifying existing ones easy:

class C(object):
    @property
    def x(self):
        "I am the 'x' property."
        return self._x
    @x.setter
    def x(self, value):
        self._x = value
    @x.deleter
    def x(self):
        del self._x
"""

1.property第一种使用方法-直接使用

从文档可以看出来,我们要使用property首先要实现几种方法,这个在上一篇文章中其实已经用过,只是没有详细说明,下面通过代码带大家探索一下。

class Person:
    def __init__(self):
        self.name = 'Tom'
        self.__money = 100

    def setMoney(self, val):
        if (isinstance(val, int) or isinstance(val, float)) and val >= 0:
            self.__money = val
        else:
            print('请输入正确的金额!')

    def getMoney(self):
        return self.__money

    # money = property(setMoney, getMoney)  # 注意两个参数的顺序不能错
    money = property(getMoney, setMoney)

per = Person()
print(per.money)
per.money = 85  # 这里是重新赋值,不是增减属性
print(per.__dict__)  # {'name': 'Tom', '_Person__money': 85},没有出现新的属性
print(per.money)

2.property第二种使用方法-property装饰器

class Person:
    def __init__(self):
        self.name = 'Tom'
        self.__money = 100

    # 先使用property装饰器让__money成为只读属性
    @property
    def money(self):
        return self.__money

    # 看下面文档
    '''
            class C(object):
            @property
            def x(self):
                "I am the 'x' property."
                return self._x
            @x.setter
            def x(self, value):
                self._x = value
            @x.deleter
            def x(self):
                del self._x
    '''
    @money.setter
    def money(self, val):
        self.__money = val

per = Person()
# per.setmoney = 56  # 这样也能设置只读属性
# print(per.__dict__)
# print(per.getmoney)
# 为了方便上面的getmoney和setmoney可以使用同名money
per.money = 56  # 这样也能设置只读属性
print(per.__dict__)
print(per.money)

 

部分文字内容为【Python自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
回顶部