Table of Contents
This guide covers classmethod ()() function in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
The Classmethod ()() Function Syntax in Python
classmethod(function)
Classmethod () Is considered un-Pythonic (Python's non-formal language), so in newer versions of Python, you should use Decor class @classmethod To determine the method
The syntax is as follows:
@classmethoddef func(cls, args.)
Parameters of Classmethod ()()
- Classmethod () Has only one parameter, Function - the function that needs to be passed into the classmethod
Value Returned from Classmethod ()()
By definition, Classmethod () Returns a class method for the given function.
So what is the class method here?
Class method is a method belonging to the whole class. When executed, it does not use any instance of that class, quite similar to staticmethod.
However there are a few differences between Static methods And Class methods Like:
- The static method Does not use anything related to the class or instance of that class but only works with parameters.
- With the Class method , the whole class will be passed into the first parameter (cls) of this method.
- The method class Can be called from both its class and object.
Class.classmethod()Or evenClass().classmethod()
The method class is always attached to the class because it implicitly assigns the class to the first parameter (cls) when calling the function.
def classMethod (cls, args .)
Example 1: Create class method (class method) using classmethod ()
class Nhanvien:tuoi = 25def printTuoi(cls):print('Số tuổi là:', cls.tuoi)# tạo phương thức class printTuoiNhanvien.printTuoi = classmethod(Nhanvien.printTuoi)Nhanvien.printTuoi()
Here, we have a Nhanvien Class , With member age variable (tuoi) Assigned to 25.
We also have a PrintTuoi Function That Takes an Uncommon Cls Parameter.
Cls accepts the Nhanvien class as a parameter instead of object / instance of Nhanvien.
Now, we pass the method Nhanvien. Print. As the argument to the classmethod function. This converts the method to a class method so that it accepts the first parameter as a class (ie Nhanvien).
In the last line, we call Print, But not create a Nhanvien Object as in the static method.
Running the above code, the program will return the result:
Số tuổi là: 25
When to Use Class Method?
1. Factory Method
Factory methods Are methods that return an object of the class in different ways.
Like loading functions in C ++, but Python is not available so here we use class methods and static methods.
Example 2: Create Factory Method Using Class Method
from datetime import date# random Nhanvienclass Nhanvien:def __init__(self, ten, tuoi):self.ten = tenself.tuoi = tuoi@classmethoddef fromBirthYear(cls, ten, birthYear):return cls(ten, date.today().year - birthYear)def ketqua(self):print("Tuổi của " + self.ten + " là: " + str(self.tuoi))nhanvien = Nhanvien('Alice', 23)nhanvien.ketqua()nhanvien1 = Nhanvien.fromBirthYear('Simon', 1990)nhanvien1.ketqua()
The program returns the result:
Tuổi của Alice là: 23Tuổi của Simon là: 28
Here we have two class instances, one created, one class method FromBirthYear.
Instance is created with the name parameter (ten) And age (tuoi), fromBirthYear Takes information from class, Ten And BirthYear And then calculates the current age using the current year subtracting the BirthYear And returning the class result instance.
The FromBirthYear Method Takes Information from the Nhanvien Class (not the Nhanvien Object ) As parameter Cls And returns a function as Cls (ten, date. Today (). Year - birthYear) Equivalent to Nhanvien (ten, date. Today) (). Year - birthYear ). This is thanks to the @classmethod Decorator . This decorator itself transforms the FromBirthYear Method of the method class with Classmethod ().
2. Create the Correct Instance in Inheritance (Inheritance).
Inheritance (inheritance) is the reuse of properties and functions of a class to define a new class. New class created is called subclass (child class or derived class), inherited class is called parent class (base class or parent class).
If you derive a class from the method factory creation using classmethod, it definitely creates the correct object in the subclass.
You can do the same but use staticmethod, the object created is definitely in the parent class.
Example 3: How the Class Method Works in Inheritance
from datetime import date# random Personclass Person:def __init__(self, name, age):self.name = nameself.age = age@staticmethoddef fromFathersAge(name, fatherAge, fatherPersonAgeDiff):return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)@classmethoddef fromBirthYear(cls, name, birthYear):return cls(name, date.today().year - birthYear)def display(self):print(self.name + "'s age is: " + str(self.age))class Man(Person):sex = 'Male'man = Man.fromBirthYear('John', 1985)print(isinstance(man, Man))man1 = Man.fromFathersAge('John', 1965, 20)print(isinstance(man1, Man))
The program returns the result:
TrueFalse
This example uses a static method to create a class with a hard-fixed data type during creation.
This caused a problem when inheriting Man From Person.
The method FromFathersAge Does not return an object in Man But returns an object in Person Class - parent class.
This violates the OOP model. Using the method class FromBirthYear Can guarantee the OOP model of the code because it takes the first parameter as the class itself is passed into its same method method.
Previous article: Function chr () in Python
Next lesson: complex () function in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.