When to use class methods in python

(*-*)浩
Release: 2019-07-09 10:15:21
Original
5468 people have browsed it

In Python, class methods are defined using the decorator @classmethod.

When to use class methods in python

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()
Copy after login

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template