Python中@staticmethod和@classmethod的区别和用法

本文详细介绍了Python中的三种方法:实例方法、类方法和静态方法。包括它们的定义方式、绑定对象及调用方式,并通过示例代码展示了classmethod和staticmethod在继承场景下的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python其实有3类方法:

  • 静态方法(staticmethod)
  • 类方法(classmethod)
  • 实例方法(instance method)

常规方式, @classmethod修饰方式, @staticmethod修饰方式.

def foo(x):
    print "executing foo(%s)" %(x)

class A(object):
    def foo(self,x):
        print "executing foo(%s,%s)" %(self,x)
    @classmethod
    def class_foo(cls,x):
        print "executing class_foo(%s,%s)" %(cls,x)
    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" %x

a = A()


1. 绑定的对象
foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定。

2. 调用方式
/实例方法类方法静态方法
a = A()a.foo(x)a.class_foo(x)a.static_foo(x)
A
不可用

A.clas_foo(x)A.static_foo(x)

3. classmethod和staticmethod的区别
直观上看,classmethod和staticmethod的函数签名不一样,一个是有参的,一个是无参的。
都属于python的装饰器,注意在classmethod里,参数不一定必须是cls,可以是任何命名的变量。在不涉及到父子类的时候,这2者行为看起来是一样的,但如果设计到父子类的时候,classmethod可以判断出调用的子类对象

# -*- coding: utf-8 -*-

class Parent(object):

    @staticmethod
    def staticSayHello():
        print "Parent static"

    @classmethod
    def classSayHello(anything):  #这里是anything
        if anything == Boy:
            print "Boy classSayHello"
        elif anything == Girl:
            print "girl sayHello"


class Boy(Parent):
     pass

class Girl(Parent):
    pass

if __name__ == '__main__':
    Boy.classSayHello()
    Girl.classSayHello()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值