Python的@staticmethod @classmethod @property

@staticmethod 静态方法

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

静态方法就是类对外部函数的封装,有助于优化代码结构、提高程序的可读性。

class myclass():
    def __init__(self):
        self.num = 1

  # 声明一个静态方法 @staticmethod def print_num(): print(self.num) print(myclass.print_num) >> 1

 

@classmethod 类方法

用于修饰类的方法,将一个类的方法指定为类方法,其作用有

  • python中不像C++一样,不支持多个参数重载构造函数,就需要采用classmethod处理函数,在对象实例化之前调用这些函数,相当于多个构造函数
  • 同staticmethod一样,可以在不创建类实例的情况下调用方法
  • 有些时候需要在实例化前就对类进行交互,这种交互可能会影响类的实例化过程,故采用classmethod
class myclass():
    def __init__(self,day=0,month=0,year=0):
        self.day =      day
        self.month = month
        self.year =     year

    @classmethod
    def deal_date(cls, data_string):    # 需要有一个cls,cls指的就是类本身
        year, month, day = map(int, data_string.split('-'))
        date1 = cls(year, month, day)

        return date1

    def out_date():
        print(year, month, day)

 

a = myclass.deal_date("2012-12-21")    # 这样就可以不修改构造函数的前提下,对不同的参数进行重构

a.out_date()

>> 20121221

 

@property

可以通过@property来创建只读属性,将方法可以像属性一样访问

@property下方的函数只能是self参数,不能有其他参数

class myclass():

    @property
    def shape(self):
        return 1,2

print(myclass.shape)
>> 1 2

 

posted @ 2022-10-26 19:59  Liang-ml  阅读(167)  评论(0)    收藏  举报