zoukankan      html  css  js  c++  java
  • python_常用装饰器函数

    1、property

      将方法伪装成属性

    2、setter   修改属性

      只有当被property装饰的方法,又实现了一个同名方法,且被setter装饰器

      装饰了,在被装饰的方法赋值的时候,就触发被setter装饰器装饰的方法

    3、deleter  删除属性

    class Student:
        def __init__(self,name):
            self.__name = name
    
        @property
        def name(self):
            return self.__name
    
        @name.setter
        def name(self,new_name):
            self.__name = new_name
    
        @name.deleter
        def name(self):
            del self.__name
    
    zhangsan = Student('张三')
    print(zhangsan.name)
    zhangsan.name = '李四'
    print(zhangsan.name)
    del zhangsan.name
    print(zhangsan.__dict__)
    View Code

     4、classmethod   类方法

    class Goods:
        __discount = 0.7
    
        def __init__(name,price):
            self.__name = name
            self.__price = price
    
        @property
        def price(self):
            return self.__price * goods.__discount
        
        @classmethod
        def chang_price(cls,new):
            cls.__discount = new
    
    a = Goods('apple',10)
    print(a.price)
    Goods.chang_price(0.8)
    print(a.price)
    View Code

    5、staticmethod  普通方法

    class Student:
        @staticmethod
        def login():
            print('登陆成功')
    View Code

    6、类中的属性与方法调用关系

      类:

        静态属性   类  所有的对象都统一拥有的属性

        类方法      类  cls默认参数

        普通方法     类       没有默认参数

        方法    对象  

        property       对象

  • 相关阅读:
    hdu2476
    zoj3469 区间dp好题
    区间dp好题cf149d 括号匹配
    cf1108e 线段树区间更新+扫描线
    完全背包记录路径poj1787 好题
    cf1104d二分+数学
    01背包专题
    hdu1069线性dp
    有源汇的上下界最大流
    有源汇的上下界最大流
  • 原文地址:https://www.cnblogs.com/echo-up/p/9562828.html
Copyright © 2011-2022 走看看