解释一: 静态函数, 类函数, 成员函数的区别?
解答:
定义:
静态函数(@staticmethod): 即静态方法,主要处理与这个类的逻辑关联;
类函数(@classmethod): 即类方法, 更关注于从类中调用方法, 而不是在实例中调用方法, 可以用作方法重载, 传入参数cls;
成员函数: 实例的方法, 只能通过实例进行调用;
具体应用:
日期的方法, 可以通过实例化(init)进行数据输出, 传入参数self;
可以通过类的方法(@classmethod)进行数据转换, 传入参数cls;
可以通过静态方法(@staticmethod)进行数据验证
class Date(object):
day = 0
month = 0
year = 0
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
def display(self):
return "{0}*{1}*{2}".format(self.day, self.month, self.year)
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
date1 = Date('12', '11', '2014')
date2 = Date.from_string('11-13-2014')
print(date1.display())
print(date2.display())
print(date2.is_date_valid('11-13-2014'))
print(Date.is_date_valid('11-13-2014'))
解释二:
oop - Python @classmethod and @staticmethod for beginner?
@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
总结:简单来说就是两个函数的逻辑都和类有关,只不过classmethod需要和类交互,staticmethod不需要和类交互