类方法、静态方法

2023-04-30  本文已影响0人  午字横
1:类方法: @classmethod

Date_test类里面创建一个成员函数, 前面用了@classmethod装饰。
它的作用就是有点像静态类,比静态类不一样的就是它可以传进来一个当前类作为第一个参数。
这样子等于先调用get_date()对字符串进行处理,然后才使用Data_test的构造函数初始化。
这样的好处就是你以后重构类的时候不必要修改构造函数,只需要额外添加你要处理的函数,
然后使用装饰符 @classmethod 就可以了


class Data(object):
    def __init__(self,time):
        self.time=time

    def output_Data(self):
        print(self.time)

    @classmethod
    def get_Data(cls,time):
        return cls(time)

d=Data("2023")
d.output_Data()

dd=Data.get_Data("2023-04")
dd.output_Data()
1:静态方法: @staticmethod

@staticmethod 用于修饰类中的方法,使其可以在不创建类实例的情况下调用方法,
这样做的好处是执行效率比较高

class Data(object):
    def __init__(self,time):
        self.time=time

    def output_Data(self):
        print(self.time)

    @classmethod
    def get_Data(cls,time):
        return cls(time)
    @staticmethod
    def show(x,y):
        print(x,y)

Data.show(1,2)
2. 实例方法、静态方法和类方法

方法包括:实例方法、静态方法和类方法,三种方法在内存中都归属于类,区别在于调用方式不同。


2023-04-27

上一篇 下一篇

猜你喜欢

热点阅读