python classmethod 和 staticmethod的区别

时间:2023-03-09 22:40:34
python classmethod 和 staticmethod的区别

https://*.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner

1.classmethod还可以调用内部的classmethod和staticmethod(是的可以调用staticmethod,cls.staticmethod)。

2.staticmethod不能调用内部的任何方法。

3.classmethod第一个参数cls表示这个类,staticmethod不需要这个参数,staticmethod只是一个函数,不能调用类内部的其它方法(可以被调用)。

#!/usr/bin/python
# -*- coding: utf-8 -*- class DateProcessor(object):
def __init__(self):
pass def parse_date(self, date_str):
print date_str
self.print_date(date_str) # 调用了calssmethod
self.print_date_1(date_str) # 调用了staticmethod @classmethod
def print_date(cls, date_str):
cls.print_date_2(date_str) # classmethod可以调用类里面其它classmethod
cls.print_date_1(date_str) # 也可以调用staticmethod
print date_str @classmethod
def print_date_2(cls, date_str):
# 可以被其它方法调用
print "date_str_2:", date_str @staticmethod
def print_date_1(date_str):
# 可以被其它方法调用,但是不能调用其它方法
print "date_str_1:", date_str if __name__ == "__main__":
date_process = DateProcessor()
date_process.parse_date("2017-06-29") # 实例化 DateProcessor.print_date("2017-06-30") # 不用实例化类,调用classmethod
DateProcessor.print_date_1("2017-06-30") # 不用实例化类,调用staticmethod