静态方法和类方法
文章目录
@staticmethod和@classmethod
Python其实有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法,如下:
|
|
self代表实例,cls代表类,实例方法和类方法的使用类似于一个偏函数(partical function)
,他们的第一个参数已经被固定的绑定为实例和类。静态方法更像是一个普通函数,他不绑定任何东西,他的出现或许仅仅是代码的风格问题,它允许你将一个普通函数绑定写到类的定义里面,假想你在写一个模块,里面有若干个类,但是需要一些普通函数来完成一些辅助工作,如果这个普通函数只是为了服务某个类,那么我们没有必要单独全局定义它,反而使用@staticmethod
会让代码更加简洁优雅。
实例方法 | 类方法 | 静态方法 |
---|---|---|
a.foo(x) | a.class_foo(x) | a.static_foo(x) |
不可用 | A.class_foo(x) | A.static_foo(x) |
注:使用a.clss_foo(x)时系统会自动查找a所对应的类 更多关于这个问题:
http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python https://realpython.com/blog/python/instance-class-and-static-methods-demystified/
文章作者 oouxx
上次更新 2019-05-18