• 【转】python之property属性


    1. 什么是property属性

    一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法

    # ############### 定义 ###############
    class Foo:
        def func(self):
            pass
    
        # 定义property属性
        @property
        def prop(self):
            pass
    
    # ############### 调用 ###############
    foo_obj = Foo()
    foo_obj.func()  # 调用实例方法
    foo_obj.prop  # 调用property属性

    如下的例子用于说明如何定一个简单的property属性:

    1 class Goods(object):
    2 
    3         @property
    4         def size(self):
    5                 return 100 
    6 
    7 
    8 g = Goods()
    9 print(g.size)

    property属性的定义和调用要注意一下几点:

    • 定义时,在实例方法的基础上添加 @property 装饰器;并且仅有一个self参数
    • 调用时,无需括号

    2. 简单的实例

    对于京东商城中显示电脑主机的列表页面,每次请求不可能把数据库中的所有内容都显示到页面上,而是通过分页的功能局部显示,所以在向数据库中请求数据时就要显示的指定获取从第m条到第n条的所有数据 这个分页的功能包括:

    • 根据用户请求的当前页和总数据条数计算出 m 和 n
    • 根据m 和 n 去数据库中请求数据
     1 # ############### 定义 ###############
     2 class Pager:
     3     def __init__(self, current_page):
     4         # 用户当前请求的页码(第一页、第二页...)
     5         self.current_page = current_page
     6         # 每页默认显示10条数据
     7         self.per_items = 10 
     8 
     9     @property
    10     def start(self):
    11         val = (self.current_page - 1) * self.per_items
    12         return val
    13 
    14     @property
    15     def end(self):
    16         val = self.current_page * self.per_items
    17         return val
    18 
    19 # ############### 调用 ###############
    20 p = Pager(1)
    21 p.start  # 就是起始值,即:m
    22 p.end  # 就是结束值,即:n

    从上述可见:

    • Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回。

    3.property属性的有两种方式

    • 装饰器 即:在方法上应用装饰器
    • 类属性 即:在类中定义值为property对象的类属性

    3.1 装饰器方式

    在类的实例方法上应用@property装饰器

    Python中的类有 经典类 新式类新式类 的属性比 经典类 的属性丰富。( 如果类继object,那么该类是新式类 )

    经典类,具有一种@property装饰器:

    1 # ############### 定义 ###############    
    2 class Goods:
    3     @property
    4     def price(self):
    5         return "laowang"
    6 # ############### 调用 ###############
    7 obj = Goods()
    8 result = obj.price  # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
    9 print(result)

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

     1 #coding=utf-8
     2 # ############### 定义 ###############
     3 class Goods:
     4     """python3中默认继承object类
     5         以python2、3执行此程序的结果不同,因为只有在python3中才有@xxx.setter  @xxx.deleter
     6     """
     7     @property
     8     def price(self):
     9         print('@property')
    10 
    11     @price.setter
    12     def price(self, value):
    13         print('@price.setter')
    14 
    15     @price.deleter
    16     def price(self):
    17         print('@price.deleter')
    18 
    19 # ############### 调用 ###############
    20 obj = Goods()
    21 obj.price          # 自动执行 @property 修饰的 price 方法,并获取方法的返回值
    22 obj.price = 123    # 自动执行 @price.setter 修饰的 price 方法,并将  123 赋值给方法的参数
    23 del obj.price      # 自动执行 @price.deleter 修饰的 price 方法

    注意:

    • 经典类中的属性只有一种访问方式,其对应被 @property 修饰的方法
    • 新式类中的属性有三种访问方式,并分别对应了三个被@property、@方法名.setter、@方法名.deleter修饰的方法

    由于新式类中具有三种访问方式,我们可以根据它们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

     1 class Goods(object):
     2 
     3     def __init__(self):
     4         # 原价
     5         self.original_price = 100
     6         # 折扣
     7         self.discount = 0.8
     8 
     9     @property
    10     def price(self):
    11         # 实际价格 = 原价 * 折扣
    12         new_price = self.original_price * self.discount
    13         return new_price
    14 
    15     @price.setter
    16     def price(self, value):
    17         self.original_price = value
    18 
    19     @price.deleter
    20     def price(self):
    21         del self.original_price
    22 
    23 obj = Goods()
    24 obj.price         # 获取商品价格
    25 obj.price = 200   # 修改商品原价
    26 del obj.price     # 删除商品原价

    3.2 类属性方式,创建值为property对象的类属性

    • 当使用类属性的方式创建property属性时,经典类新式类无区别
    1 class Foo:
    2     def get_bar(self):
    3         return 'laowang'
    4 
    5     BAR = property(get_bar)
    6 
    7 obj = Foo()
    8 reuslt = obj.BAR  # 自动调用get_bar方法,并获取方法的返回值
    9 print(reuslt)

    property方法中有个四个参数

    • 第一个参数是方法名,调用 对象.属性 时自动触发执行方法
    • 第二个参数是方法名,调用 对象.属性 = XXX 时自动触发执行方法
    • 第三个参数是方法名,调用 del 对象.属性 时自动触发执行方法
    • 第四个参数是字符串,调用 对象.属性.__doc__ ,此参数是该属性的描述信息
     1 #coding=utf-8
     2 class Foo(object):
     3     def get_bar(self):
     4         print("getter...")
     5         return 'laowang'
     6 
     7     def set_bar(self, value): 
     8         """必须两个参数"""
     9         print("setter...")
    10         return 'set value' + value
    11 
    12     def del_bar(self):
    13         print("deleter...")
    14         return 'laowang'
    15 
    16     BAR = property(get_bar, set_bar, del_bar, "description...")
    17 
    18 obj = Foo()
    19 
    20 obj.BAR  # 自动调用第一个参数中定义的方法:get_bar
    21 obj.BAR = "alex"  # 自动调用第二个参数中定义的方法:set_bar方法,并将“alex”当作参数传入
    22 desc = Foo.BAR.__doc__  # 自动获取第四个参数中设置的值:description...
    23 print(desc)
    24 del obj.BAR  # 自动调用第三个参数中定义的方法:del_bar方法

    由于类属性方式创建property属性具有3种访问方式,我们可以根据它们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

    class Goods(object):
    
        def __init__(self):
            # 原价
            self.original_price = 100
            # 折扣
            self.discount = 0.8
    
        def get_price(self):
            # 实际价格 = 原价 * 折扣
            new_price = self.original_price * self.discount
            return new_price
    
        def set_price(self, value):
            self.original_price = value
    
        def del_price(self):
            del self.original_price
    
        PRICE = property(get_price, set_price, del_price, '价格属性描述...')
    
    obj = Goods()
    obj.PRICE         # 获取商品价格
    obj.PRICE = 200   # 修改商品原价
    del obj.PRICE     # 删除商品原价

    综上所述:

    • 定义property属性共有两种方式,分别是【装饰器】和【类属性】,而【装饰器】方式针对经典类和新式类又有所不同。
    • 通过使用property属性,能够简化调用者在获取数据的流程

    4. property属性-应用

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

     1 class Money(object):
     2     def __init__(self):
     3         self.__money = 0
     4 
     5     def getMoney(self):
     6         return self.__money
     7 
     8     def setMoney(self, value):
     9         if isinstance(value, int):
    10             self.__money = value
    11         else:
    12             print("error:不是整型数字")

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

     1 class Money(object):
     2     def __init__(self):
     3         self.__money = 0
     4 
     5     def getMoney(self):
     6         return self.__money
     7 
     8     def setMoney(self, value):
     9         if isinstance(value, int):
    10             self.__money = value
    11         else:
    12             print("error:不是整型数字")
    13 
    14     # 定义一个属性,当对这个money设置值时调用setMoney,当获取值时调用getMoney
    15     money = property(getMoney, setMoney)  
    16 
    17 a = Money()
    18 a.money = 100  # 调用setMoney方法
    19 print(a.money)  # 调用getMoney方法
    20 #100

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

    • 重新实现一个属性的设置和读取方法,可做边界判定
     1 class Money(object):
     2     def __init__(self):
     3         self.__money = 0
     4 
     5     # 使用装饰器对money进行装饰,那么会自动添加一个叫money的属性,当调用获取money的值时,调用装饰的方法
     6     @property
     7     def money(self):
     8         return self.__money
     9 
    10     # 使用装饰器对money进行装饰,当对money设置值时,调用装饰的方法
    11     @money.setter
    12     def money(self, value):
    13         if isinstance(value, int):
    14             self.__money = value
    15         else:
    16             print("error:不是整型数字")
    17 
    18 a = Money()
    19 a.money = 100
    20 print(a.money)

    转载出处https://www.cnblogs.com/zhangfengxian/p/10199935.html

    --------------------成功,肯定是需要一点一滴积累的--------------------
  • 相关阅读:
    Linux驱动入门(三)Led驱动
    Linux驱动入门(二)操作硬件
    mysql表的完整性约束
    数据库操作
    初识数据库
    mysql的安装、启动和基础配置 —— windows版本
    Socket网络编程
    python进阶之多线程(简单介绍协程)
    python进阶多进程(进程池,进程间通信)
    python基础之异常处理
  • 原文地址:https://www.cnblogs.com/GouQ/p/11772716.html
Copyright © 2020-2023  润新知