时间:2021-07-01 10:21:17 帮助过:487人阅读
我们直接看例子。(推荐学习: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_inst ik1 = Kls() ik2 = Kls() print ik1.get_no_of_instance() print Kls.get_no_of_instance()
类方法用在模拟java定义多个构造函数的情况。
由于python类中只能有一个初始化方法,不能按照不同的情况初始化类。
coding:utf-8 class Book(object): def __init__(self, title): self.title = title @classmethod def class_method_create(cls, title): book = cls(title=title) return book @staticmethod def static_method_create(title): book= Book(title) return book book1 = 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教程栏目进行学习!
以上就是python什么时候用类方法的详细内容,更多请关注Gxl网其它相关文章!