• property属性


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

    设置方式:

    类属性 即:在类中定义值为property对象的类属性 ---推荐

     1 class Money(object):
     2     # 初始化空间
     3     def __init__(self,money):
     4         self.__money = money
     5     # 获取价钱
     6     def __getMoney(self):
     7         return self.__money
     8     # 设置价钱
     9     def __setMoney(self,value):
    10         if isinstance(value,int):
    11             self.__money = value
    12         else:
    13             print("error:不是整数")
    14     # 删除价钱
    15     def __delMoney(self):
    16         self.__money = None
    17         return self.__money
    18     # 创建property属性
    19     # property(获取,设置,删除,介绍)
    20     money = property(__getMoney,__setMoney,__delMoney,"价钱")
    21 # 实例化对象
    22 tao = Money(20)
    23 # 获取价钱
    24 print(tao.money)
    25 # 设置价钱
    26 tao.money = 100
    27 print(tao.money)
    28 # 查看属性介绍
    29 print(tao.__class__.money.__doc__)
    30 # 删除价钱
    31 del tao.money
    32 print(tao.money)

    运行结果:

    20
    100
    价钱
    None
    

      

    装饰器 即:

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

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

    经典类中只有获取 ,新式类中有3中方式

    经典类:

     1 class Goods:
     2     @property
     3     # price只传一个只就是它自己
     4     def price(self):
     5         return 100
     6 
     7 
     8 #调用
     9 obj = Goods();
    10 print(obj.price)  # 自动执行 @price 修饰的 price方法,并获取方法的返回值

    运行结果:

    100
    

      

    新式类:

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

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

     1 class Goods(object):
     2     @property
     3     # price只传一个只就是它自己
     4     def price(self):
     5         return 100
     6 
     7     @property.setter
     8     def price(self,value):
     9         if isinstance(value,int):
    10             self.price = value
    11         else:
    12             print("error:请输入整数")
    13 
    14     @property.deleter
    15     def price(self):
    16         del self.price
    17 
    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 方法
  • 相关阅读:
    axios全局配置
    014 Javascript(148
    013 Javascript(134
    axios的基本使用
    axios简介
    012 Javascript(126
    016 HTML+CSS(Class198
    015 HTML+CSS(Class184
    014 HTML+CSS(Class165
    LCA题目选讲2
  • 原文地址:https://www.cnblogs.com/yifengs/p/11437445.html
Copyright © 2020-2023  润新知