python中普通方法、静态方法与类方法之间的区别

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)

参考资料:
Difference between @staticmethod and @classmethod

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值