Normal method、classmethod、staticmethod三者区别
- 普通方法,nomal method:当前对象自动作为(附加)第一个参数传递给方法
- 类方法,class method:当前对象的类自动作为(附件)第一个参数传递给方法
- 静态方法,static method: 不会自动传递额外的参数,你传递给函数的参数就是方法得到的参数。
Nomal method 普通方法
“标准”方法,就像在每一个面向对象的语言中一样。当一个对象的方法被调用时,它会自动获得一个额外的参数self
作为它的第一个参数,也就是方法:
def f(self, x, y)
必须用2个参数调用。self
是自动传递的,而且是对象本身。类似于this
神奇的出现在java/c++,只有在python中才会显式显示。
class method 类方法
- 用类名作为第一个参数的函数
- 可以通过类和实例调用
- 是使用classmethod内置函数创建定的
装饰方法时:
@classmethod
def f(cls, x, y)
自动提供的参数不是self
,而是类本身
static method 静态方法
- 没有self参数的简单方法
- 处理类属性;不在实例属性上。
- 可以通过类和实例调用
- 内置函数staticmethod()用于创建他们
装饰方法时:
@staticmethod
def f(x, y)
该方法根本没有给出任何自动参数。它只给出调用它的参数。
用途
classmethod
主要用于替代构造函数staticmethod
不使用对象的状态,甚至不使用类本身的结构。它可以是类外部的函数。它只放在类中,用于对具有相似功能的函数进行分组(例如,像Java的Math
类静态方法)
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def frompolar(cls, radius, angle):
"""The 'cls' argument is the 'Point' class itself"""
return cls(radius * cos(angle), radius * sin(angle))
@staticmethod
def angle(x, y):
"""this could be outside the class, but we put it here just because we think it is logically related to the class."""
return atan(y, x)
p1 = Point(3, 2)
p2 = Point.frompolar(3, pi/4)
angle = Point.angle(3, 2)