首页  

python 属性访问器     所属分类 python 浏览量 23
@property 用于定义 属性访问器 的装饰器,
将类的方法“伪装”成属性,从而实现对属性的 访问控制 和 逻辑封装。

通过 @property 和对应的 @attribute.setter,可以在属性被读取或修改时添加验证逻辑
@attribute.deleter:定义属性删除时的逻辑。
只读属性:仅定义 @property,不定义 @attribute.setter 



普通方法:需要调用 obj.method(),适合执行操作。
属性访问器:直接使用 obj.attribute,适合返回状态或数据。

class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        return self.width * self.height

访问 rectangle.area 时,实时计算面积,无需存储额外数据。


不使用属性访问器 class BankAccount: def __init__(self, balance): self.balance = balance def get_balance(self): return self.balance def set_balance(self, value): if value < 0: raise ValueError("余额不能为负数") self.balance = value account = BankAccount(100) print(account.get_balance()) # 需要显式调用方法 account.set_balance(200) # 需要显式调用方法 account.set_balance(-100) 使用属性访问器 class BankAccount: def __init__(self, balance): self.balance = balance # 通过 setter 验证 @property def balance(self): return self._balance @balance.setter def balance(self, value): if value < 0: raise ValueError("余额不能为负数") self._balance = value account = BankAccount(100) print(account.balance) # 像属性一样访问 account.balance = 200 # 像属性一样赋值 print(account.balance)

上一篇     下一篇
葛兰威尔均线八大法则

python 发送http请求获取行情数据实例

Python 类型提示(Type Hints)

Python知识点及代码示例