python什么时候用类方法
在python中类方法(class method)采用装饰器@classmethod来定义。
我们直接看例子。(推荐学习:Python视频教程)
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_instik1 = Kls()ik2 = Kls()print ik1.get_no_of_instance()print Kls.get_no_of_instance()
类方法用在模拟java定义多个构造函数的情况。
由于python类中只能有一个初始化方法,不能按照不同的情况初始化类。
立即学习“Python免费学习笔记(深入)”;
coding:utf-8class Book(object):def __init__(self, title):self.title = title @classmethoddef class_method_create(cls, title):book = cls(title=title)return book @staticmethoddef static_method_create(title):book= Book(title)return bookbook1 = Book("use instance_method_create book instance")book2 = Book.class_method_create("use class_method_create book instance")book3 = Book.static_method_create("use static_method_create book instance")print(book1.title)print(book2.title)print(book3.title)
更多Python相关技术文章,请访问Python教程栏目进行学习!