本文摘自php中文网,作者(*-*)浩,侵删。
在Python中类方法(class method)采用装饰器@classmethod来定义。
我们直接看例子。(推荐学习:Python视频教程)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Kls(object):
num_inst = 0
def __init__(self):
Kls.num_inst = Kls.num_inst + 1
@classmethod
def get_no_of_instance(cls):
return cls.num_inst
ik1 = Kls()
ik2 = Kls()
print ik1.get_no_of_instance()
print Kls.get_no_of_instance()
|
类方法用在模拟java定义多个构造函数的情况。
由于python类中只能有一个初始化方法,不能按照不同的情况初始化类。
阅读剩余部分
相关阅读 >>
Python能做什么?是什么?
Python表达式是什么
Python全栈工程师是什么意思
Python人工智能难吗
详解Python的命名规则
Python都有哪些框架
Python中format怎么用
Python md5与sha1加密算法的详细介绍
Python中给list添加元素的4种方法分享_Python
Python怎么安装有setup.py的包
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python什么时候用类方法