Python中的@staticmethod,@classmethod,self,cls到底是什么意思?

普通类方法

在Python中,通常我们调用某个类的方式,首先要实例化一个对象才能调用该类的方法,比如:

# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

# 实例化一个对象
LiMing = People()
LiMing.hello()

"""""""""""""""""""""
输出:hello everyone
"""""""""""""""""""""

使用@staticmethod 和@classmethod 方法修饰

当我们使用@staticmethod 和@classmethod 修饰后,则不需要实例化就可以直接调用类方法,下面举例说明:

# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

    @staticmethod
    def say_morning():
        print("good morning")

    @classmethod
    def say_afternoon(cls):
        print("good afternoon")


# 实例化一个对象
LiMing = People()
LiMing.hello()
# 使用@staticmethod 或者使用@classmethod 不需要实例化就可以直接调用类方法
People.say_morning()
People.say_afternoon()

"""""""""""""""""""
这里是输出:
hello, Everyone.
good morning
good afternoon
"""""""""""""""""""

self和cls以及@staticmethod 和@classmethod修饰的区别

使用@staticmethod 和@classmethod 都不需要实例化就可以直接调用类方法,但是两者还是有区别的,我们知道:

  • @staticmethod:不需要表示对象的self和自身类的clas参数,就和使用函数一样
  • @classmethod:不需要self,但第一个参数需要是表示自身类的cls参数。
    使用表示自身的cls参数之后,@classmethod装饰的函数就可以使用类本身的方法。下面我们举例进行说明:
# _*_ coding:utf_8 _*_
class People:
    def hello(self):
        print("hello, Everyone.")

    @staticmethod
    def say_morning():
        print("good morning")
        # print(People.hello())  这里会报错!

    @classmethod
    def say_afternoon(cls):
        print("good afternoon")
        print(cls().hello())


# 实例化一个对象
LiMing = People()
LiMing.hello()

People.say_morning()
People.say_afternoon()

"""""""""""""""""""
这里是输出:
hello, Everyone.
good morning
good afternoon
hello, Everyone.
"""""""""""""""""""
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值