Django directly defines the properties of the class and can be called directly in instantiated objects or classes.
Class attributes:version_number is a class attribute that is shared among all instances. It is initialized when the class is loaded.
class Book: version_number = "1.0.0" def __init__(self, title, author): = title = author @classmethod def get_version(cls): return cls.version_number #Use class methodsprint(Book.get_version()) # Output: 1.0.0
When do you need a class method?@classmethod):
1. If you need to define a method, it needs to access class-level data (such as class properties);
2. Defining the class method is to have otherMethods other than this class can also be called。
3. If you need to define a method, you need to be in the methodUse cls to create an instance of a class
4. Perform other class-related operations, then you should use @classmethod.
class Book: version_number = "1.0.0" def __init__(self, title, author): = title = author @classmethod def get_version(cls): return cls.version_number #Use class methodsprint(Book.get_version()) # Output: 1.0.0
In this example, get_version is a class method that is declared through the @classmethod decorator, allowing you to access the class property version_number. If your requirements are similar, then you need to use class methods. Otherwise, if you just need to execute a function at class definition and store the result as a class property, you don't need to define it as a class method.
This is the end of this article about the implementation of class attributes and class methods in django. For more related contents of django class attributes and class methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!