python-staticmethod和classmethod

classmethod 和 staticmethod 非常相似,但在用法上依然有一些明显的区别。classmethod 必须有一个指向 类对象 的引用作为第一个参数,而 staticmethod 可以没有任何参数。

staticmethod 没有任何必选参数,而 classmethod 第一个参数永远是 cls, instancemethod 第一个参数永远是 self。

静态方法的使用中,我们不会访问到 class 本身 – 它基本上只是一个函数,在语法上就像一个方法一样,但是没有访问对象和它的内部(字段和其他方法),相反 classmethod 会访问 cls, instancemethod 会访问 self。

1 @classmethod
2   def from_string(cls, date_as_string):
3   day, month, year = map(int, date_as_string.split('-'))
4   date1 = cls(day, month, year)
5   return date1
6  
7  
8 date2 = Date.from_string('11-09-2012')
类方法使用
1 @staticmethod
2 def is_date_valid(date_as_string):
3   day, month, year = map(int, date_as_string.split('-'))
4   return day <= 31 and month <= 12 and year <= 3999
5  
6 # usage:
7 is_date = Date.is_date_valid('11-09-2012')
静态方法使用

区别总结:

  1. 静态方法装饰器下定义的方法属于函数(function);
  2. 类方法装饰器下定义的方法属于方法(method);
  3. 静态方法无需传入任何参数;
  4. 类方法传入的第一个参数必须是class本身cls;
  5. 静态方法与类方法一旦被调用,内存地址即确定。通过类调用和通过实例化对象调用的结果完全一样。

猜你喜欢

转载自www.cnblogs.com/benchdog/p/9294598.html