zoukankan      html  css  js  c++  java
  • 网络编程-Python高级语法-property属性

    知识点:

                一、什么是property属性? 一种用起来像是使用的实例属性一样的特殊属性,可以对应于某个方法,Python的property属性的功能是:property属性内部进行一系列的逻辑计算,最终将计算结果返回。

                二、property属性的有两种方式 :         

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

                    1、使用装饰器时经典类和新式类的区别:

                        经典类中:property属性只有装饰器@property这一个    

                        新式类中:具有三种@property装饰器,分别对应了三个被@property、@方法名.setter、@方法名.deleter修饰的方法,我们可以根据它们几个属性的访问特点,分别将三个方法定义为对同一个属性:获取、修改、删除

                    2、当使用类属性的方式创建property属性时,经典类新式类无区别

                  

    1、使用装饰器创建property属性的具体代码例子:

    """1、使用@property装饰器时,下面跟着的方法只有一个self参数,不会有其他参数,这个一般是获取这个方法的返回值,
       2、如果要传值的话,就使用@获取方法的函数名.setter,后面跟着的方法可以而且只能传一个参数
       3、为什么使用property属性:使用property属性后,调用类里面的方法时不需要加括号,这也是省去了调用方法时还要查看要不要传参的麻烦
                                 而且简洁明了
    """
    class Money(object):
        def __init__(self):
            self.__money = 0
    
        # 获取方法返回的值
        @property
        def get_money(self):  # 只能有一个self参数
            return self.__money
    
        @get_money.setter
        def set_money(self,value):  # 只能有一个self和传递一个参数
            if isinstance(value,int):
                self.__money = value
            else:
                print('输入的不是整数')
    
    
    money = Money()  # 创建实例对象
    money.set_money = 200  # 给方法传参
    c = money.get_money  # 获取方法的返回值
    print(c)

    打印结果:
    200

    2、使用类属性创建property属性

    class Money(object):
        def __init__(self):
            self.__money = 0
    
        def set_money(self,value):
            self.__money = value
    
        def get_money(self):
           return self.__money
        MONEY = property(get_money, set_money)  # 这里函数放的顺序是从(获取,设置,删除)排的,不要搞错,我这里没有写删除,因为用的不多
    
    
    mon = Money()
    mon.MONEY = 50
    val = mon.MONEY
    print(val)

      

  • 相关阅读:
    thymeleaf常用属性
    spring的jdbcTemplate的使用
    spring使用thymeleaf
    thymeleaf介绍
    struts2请求过程源码分析
    Git 学习笔记之(三)将本地工程导入到GitHub 仓库中
    spring boot 学习笔记(三)之 配置
    Zookeeper 学习笔记(一)之功能介绍
    Git 学习笔记之(一) 使用 git gui 从github上下载代码
    Linux 清理空间
  • 原文地址:https://www.cnblogs.com/lz-tester/p/9474972.html
Copyright © 2011-2022 走看看