1. 类实例方法
在类中定义的方法默认都是实例方法。类方法不用实例化类也可调用,但是必须有一个self参数。
# 定义类A
class A:
def __init__(self):
self.var = 3
def get_var(self):
return self.var
# python中类中的方法与函数无异
>>>A.get_var
<function A.get_var at 0x0000014559EC11F0>
>>>A.get_var()
Traceback (most recent call last):
File "D:\software\anaconda\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
TypeError: get_var() missing 1 required positional argument: 'self'
# 需要传入一个实例的类才能调用成功
>>>A.get_var(A())
3
2. 静态方法 @staticmethod
如果不想传入self参数,并且想使用该类中的方法,或者不想实例化类可使用 @staticmethod装饰器。可将其当作一般函数使用,有利于减少不必要的内存和性能消耗。
class