当前位置:脚本大全 > > 正文

python 常用模块函数(Python OOP类中的几种函数或方法总结)

时间:2022-01-26 01:25:28类别:脚本大全

python 常用模块函数

Python OOP类中的几种函数或方法总结

概述

实例方法

静态方法

类方法

装饰器版:

classmethod(function)版:

普通函数

总而言之,除了装饰器版的类方法和静态方法外,其它方法与函数均可看做是实例方法.

代码与运行结果

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • class A(object):
  •   def instant_method(self,*args):
  •     print('实例方法',*args)
  •   @classmethod
  •   def class_method_01(clz,*args):
  •     """第一个参数为class,调用时自动传递"""
  •     print('类方法(装饰器版)',*args)
  •   def class_method_02(*args):
  •     print('类方法(普通函数通过内置函数classmethond(function)转换版)',*args)
  •   classmethod(class_method_02)
  •   @staticmethod
  •   def static_method(*args):
  •     print('静态方法',*args)
  •   def normal_function(*args):
  •     print('普通函数',*args)
  • a=A()
  • # 调用实例方法
  • a.instant_method('通过实例调用')
  • A.instant_method(a,'通过类调用')
  • # 调用装饰器版类方法
  • a.class_method_01('通过实例调用')
  • A.class_method_01('通过类调用')
  • # 调用classmethod(function)版类方法
  • # 通过实例调用时,会默认传递实例本身到方法的第一个参数
  • a.class_method_02('通过实例调用')
  • A.class_method_02('通过类调用')
  • # 调用静态方法
  • a.static_method('通过实例调用')
  • A.static_method('通过类调用')
  • # 调用普通函数
  • # 通过实例调用时,会默认传递实例本身到方法的第一个参数
  • a.normal_function('通过实例调用')
  • A.normal_function('通过类调用')
  • 输出

    实例方法 通过实例调用
    实例方法 通过类调用
    类方法(装饰器版) 通过实例调用
    类方法(装饰器版) 通过类调用
    类方法(普通函数通过内置函数classmethond(function)转换版) <main.A object at 0x7f9b9b0486a0> 通过实例调用
    类方法(普通函数通过内置函数classmethond(function)转换版) 通过类调用
    静态方法 通过实例调用
    静态方法 通过类调用
    普通函数 <main.A object at 0x7f9b9b0486a0> 通过实例调用
    普通函数 通过类调用

    总结

    以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对开心学习网的支持。如果你想了解更多相关内容请查看下面相关链接

    原文链接:https://blog.csdn.net/topleeyap/article/details/79157273

    标签:
    上一篇下一篇

    猜您喜欢

    热门推荐