我所理解的实例方法、类方法(@classmethod)和静态方法(@staticmethod)(关键词:实例方法/类方法/@classmethod/静态方法/@staticmethod)
2017-08-07 17:42
585 查看
分别用一句话解释:
实例方法:在类中,定义的方法,这个方法的第一个参数默认是实例对象。一般习惯使用self。
类方法: 在类中,定义的方法,这个方法的第一个参数默认是类对象。 一般习惯使用cls。使用@classmethod装饰器装饰。
静态方法:在类中,定义的方法,这个方法的参数没有要求。 使用@staticmethod装饰器装饰。
实例方法只能被实例调用。
类方法和静态方法可以被类或者实例调用。
什么意思?直接上代码:
参考文献:
1.python类的静态方法和类方法区别
实例方法:在类中,定义的方法,这个方法的第一个参数默认是实例对象。一般习惯使用self。
类方法: 在类中,定义的方法,这个方法的第一个参数默认是类对象。 一般习惯使用cls。使用@classmethod装饰器装饰。
静态方法:在类中,定义的方法,这个方法的参数没有要求。 使用@staticmethod装饰器装饰。
实例方法只能被实例调用。
类方法和静态方法可以被类或者实例调用。
什么意思?直接上代码:
class Foo(object): # 实例方法,第一个参数必须是实例对象。一般习惯用self。 def instance_method(self): print("是类{}的实例方法,只能被实例对象调用".format(Foo)) # 类方法, 第一个参数必须是类 对象。一般习惯使用cls。使用@classmethod装饰器装饰。 @classmethod def class_method(cls): print("是类方法") # 静态方法,参数没有要求。 使用@staticmethod装饰器装饰。 @staticmethod def static_method(): print("是静态方法") foo = Foo() # 实例方法只能被实例调用。 foo.instance_method() print('----------') # 类方法可以被类或者实例调用。 Foo.class_method() foo.class_method() print('----------') # 静态方法可以被类或者实例调用。 Foo.static_method() foo.static_method()
参考文献:
1.python类的静态方法和类方法区别
相关文章推荐
- python 类中@staticmethod,@classmethod和实例方法
- 粗解python的@classmethod和@staticmethod及普通实例方法
- Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- 转 Python 实例方法、@staticmethod和@classmethod
- python中@staticmethod 、@classmethod 与一般方法的区别
- 【再回首Python之美】【类-三种方法】绑定方法、@staticmethod、@classmethod的基本使用
- Python使用@staticmethod和@classmethod分别建立方法
- Python 实例方法、@staticmethod和@classmethod
- 我所理解的类方法(classmethod)(关键词:类方法/ClassMethod)
- 我所理解的【实例.方法()/instance.method()/类.方法(实例)/class.method(instance)】
- 记录一个 关于 python 普通方法,静态方法和类方法 的介绍。@classmethod @staticmethod
- 使用Repository模式时用静态方法(static)还是实例方法
- Python学习笔记 --- @staticmethod 和 @classmethod方法的使用
- python的静态方法以及@staticmethod或@classmethod的区别
- Python 实例方法、@staticmethod和@classmethod
- 理解python:@classmethod 和@staticmethod
- 新手理解@classmethod及@staticmethod
- 5.Static ,protect,属性和方法,静态方法(static)和实例方法,JAVA的静态变量、静态方法、静态类
- 自己理解的javascript静态方法和动态实例方法区别