python 23 --面向对象(4)-- 类的方法和属性(下)-- 类实例方法,类方法,类静态方法

类成员方法与静态方法

类的方法也有不同的种类:

  • 实例方法
  • 类方法
  • 静态方法

前文定义的所有类的方法都是实例方法,其隐含调用参数是类的实例。类方法隐含调用参数是类,而静态方法没有隐含调用参数。类方法和静态方法的定义方式都与实例方法不同,他们的调用方式也不同

静态方法定义时应使用装饰器@staticmethod进行修饰,是没有默认参数的;类方法定义时使用装饰器@classmethod进行修饰,必须有默认参数“cls”。他们的调用方式可以直接由类名进行调用,调用前也可以不实例化类,当然也可以用该类的任一个实例来进行调用

>>> class DemoMthd:
...     @staticmethod
...     def static_mthd():
...             print('static method called!')
...     @classmethod
...     def class_mthd(cls):
...             print('class method called!')
... 
>>> DemoMthd.static_mthd()
static method called!
>>> DemoMthd.class_mthd()
class method called!
>>> dm = DemoMthd()
>>> dm.static_mthd()
static method called!
>>> dm.class_mthd()
class method called!

在静态方法和类方法中不能使用实例属性,因为有可能在调用时还没有实例化

发布了64 篇原创文章 · 获赞 6 · 访问量 5550

猜你喜欢

转载自blog.csdn.net/weixin_45494811/article/details/104175933