概述
实例方法
静态方法
类方法
装饰器版:
classmethod(function)版:
普通函数
总而言之,除了装饰器版的类方法和静态方法外,其它方法与函数均可看做是实例方法.
代码与运行结果
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> 通过实例调用
普通函数 通过类调用
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。