classmethod和staticmethod装饰器

复制代码
"""
两个装饰器
    @classmethod   把一个对象绑定的方法,修改成为一个类方法
        1.在方法中仍然可以引用类中的静态变量
        2.可以不用实例化对象,就直接使用类名在外部调用这个方法
    什么时候用?
        1.定义了一个方法,默认传参self,但这个self没有被使用
        2.并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候



    @staticmethod
        静态方法

"""

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

apple = Goods()
print(apple.price)

Goods.change_discount(0.6)
apple1 = Goods()
print(apple1.price)




# 在自己类里面实例化
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 = Date.today()
print(date.year)
print(date.month)
print(date.day)


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

class User:
    pass

    @staticmethod
    def login():        #本身是一个普通的函数,被移到类的内部执行,那么直接给这个函数添加@staticmethod就可以了
        print("登录")
        # 在函数内部既不会用到self,也不会用到cls时用

User.login()
复制代码

 

posted @   Wchime  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示