• 两个装饰函数


    两个装饰函数

    classmethod 被装饰的方法会成为一个静态方法

    class Goods:
        __discount = 0.8
        def __init__(self):
            self.__price = 5
            self.price = self.__price * self.__discount
        @classmethod   # 把一个对象绑定的方法 修改成一个 类方法
        def change_discount(cls,new_discount):
            cls.__discount = new_discount
            
    Goods.change_discount(0.6)   # 类方法可以通过类名调用
    apple = Goods()
    print(apple.price)
    apple.change_discount(0.5)  # 类方法可以通过对象名调用
    apple2 = Goods()
    print(apple2.price)
    # @classmethod   # 把一个对象绑定的方法 修改成一个 类方法
    # 第一,在方法中仍然可以引用类中的静态变量
    # 第二,可以不用实例化对象,就直接用类名在外部调用这个方法
    # 什么时候用@classmethod?
        # 1.定义了一个方法,默认传self,但这个self没被使用
        # 2.并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候
    
    import time
    class Date:
        def __init__(self,year,month,day):
            self.year = year
            self.month = month
            self.day = day
        @classmethod
        def today(cls):
            struct_t = time.localtime()
            date = cls(struct_t.tm_year,struct_t.tm_mon,struct_t.tm_mday)
            return date
    
    date对象 = Date1.today()
    print(date对象.year)
    print(date对象.month)
    print(date对象.day)
    

    @staticmethod 被装饰的方法会成为一个静态方法

    class User:
        pass
        @staticmethod
        def login(a,b):      # 本身是一个普通的函数,被挪到类的内部执行,那么直接给这个函数添加@staticmethod装饰器就可以了
            print('登录的逻辑',a,b)
            # 在函数的内部既不会用到self变量,也不会用到cls类
    obj = User()
    User.login(1,2)
    obj.login(3,4)
    
  • 相关阅读:
    Bootstrap 2.2.2 的新特性
    Apache POI 3.9 发布,性能显著提升
    SQL Relay 0.48 发布,数据库中继器
    ProjectForge 4.2.0 发布,项目管理系统
    红帽企业 Linux 发布 6.4 Beta 版本
    红薯 快速的 MySQL 本地和远程密码破解
    MariaDB 宣布成立基金会
    Percona XtraBackup 2.0.4 发布
    Rocks 6.1 发布,光盘机群解决方案
    精通Servlet研究,HttpServlet的实现追究
  • 原文地址:https://www.cnblogs.com/wyh0717/p/13245865.html
Copyright © 2020-2023  润新知