In Python, class methods are defined using the decorator @classmethod.
Let’s look directly at the example. (Recommended learning: Python video tutorial)
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()
Class method is used to simulate the situation where java defines multiple constructors.
Since there can only be one initialization method in a python class, the class cannot be initialized according to different situations.
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)
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of When to use class methods in python. For more information, please follow other related articles on the PHP Chinese website!