Python-property属性

property 属性

类函数通过property属性的处理,调用该函数方法时可以直接调用,相当于调用类属性一样不用加括号。

property属性有2中方式

1、装饰器方式(经典类和新式类)
经典类,只有@property装饰器:

class Paper:
    # 类属性
    length = 1.8

    def __init__(self,  color):
        # 实例属性
        self.color = color

    @property
    def common_func(self):
        return self.color


if __name__ == '__main__':
    p = Paper("yello")
    result = p.common_func
    print(result)

输出:

"C:\Program Files\Python39\python.exe" E:/caicai/test.py
yello

Process finished with exit code 0

新式类,有三种@property装饰器

class Paper(object):

    def __init__(self):
        # 实例属性
        self.per_length = 2
        self.num = 3

    @property
    def length(self):
        new_length = self.per_length * self.num
        return new_length

    @length.setter
    def length(self, value):
        self.per_length = value

    @length.deleter
    def length(self):
        del self.per_length


if __name__ == '__main__':
    p = Paper()
    p.length	# 获取长度属性
    print(p.length)
    p.length = 3  # 修改长度属性
    print(p.length)
    del p.length  # 删除长度属性
    print(p.length) # 删除后输出报错,该属性不存在

输出如下:

"C:\Program Files\Python39\python.exe" E:/caicai/property_test.py
Traceback (most recent call last):
6
  File "E:\caicai\property_test.py", line 30, in <module>
9
    print(p.length)
  File "E:\caicai\property_test.py", line 10, in length
    new_length = self.per_length * self.num
AttributeError: 'Paper' object has no attribute 'per_length'

Process finished with exit code 1

2、类属性方式

class Paper(object):

    def __init__(self):
        # 实例属性
        self.per_length = 2
        self.num = 3

    def get_length(self):
        new_length = self.per_length * self.num
        return new_length

    def set_length(self, value):
        self.per_length = value

    def del_length(self):
        del self.per_length

    LENGTH = property(get_length, set_length, del_length, "属性描述....")


if __name__ == '__main__':
    p = Paper()
    p.LENGTH # 获取长度属性
    print(p.LENGTH)
    p.LENGTH = 3 # 修改长度属性
    print(p.LENGTH)
    del p.LENGTH # 删除长度属性
    print(p.LENGTH)

输出如下:

"C:\Program Files\Python39\python.exe" E:/caicai/property_test.py
Traceback (most recent call last):
6
  File "E:\caicai\property_test.py", line 30, in <module>
9
    print(p.length)
  File "E:\caicai\property_test.py", line 10, in length
    new_length = self.per_length * self.num
AttributeError: 'Paper' object has no attribute 'per_length'

Process finished with exit code 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值