Thứ Tư, Tháng Hai 12, 2025
spot_img
Homeclassmethod() function in Python - QuanTriMang.com

classmethod() function in Python – QuanTriMang.com

In Python, classmethod() function returns a class method for the function. Function syntax classmethod() How, what parameters does it have and how to use it? We invite readers to follow along.

Classmethod() function syntax in Python

classmethod(function)

classmethod() is considered un-Pythonic (Python's unofficial language), so in newer versions of Python you should use decorators @classmethod to determine the method

The syntax is as follows:

@classmethod
def func(cls, args...)

Parameters of classmethod() function

  • classmethod() there is only one parameter function – the function needs to be passed into the classmethod

Return value 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 that belongs to the entire class. When executed, it does not use any instance of that class, quite similar to staticmethod.

However there are a few differences between static method and class method like:

  • static method Do not use anything related to the class or instance of that class but only work with parameters.
  • With class method then the entire class will be passed as the first parameter (cls) of this method.
  • Class method can be called from both the class and its object.
Class.classmethod()
Or even
Class().classmethod()

Class methods are always attached to the class because they implicitly assign the class to the first parameter (cls) when calling the function.

def classMethod(cls, args...)

Example 1: Create a class method using classmethod()

class Nhanvien:
tuoi = 25

def printTuoi(cls):
print('Số tuổi là:', cls.tuoi)

# tạo phương thức class printTuoi
Nhanvien.printTuoi = classmethod(Nhanvien.printTuoi)

Nhanvien.printTuoi()

Here, we have a class Nhanvien, with member age variable (age) assigned to 25.

We also have a function printTuoi take a parameter cls not commonly used.

cls accepts class Nhanvien as a parameter instead of object/instance's Nhanvien.

Now, we pass the method Nhanvien.printTuoi as an argument to the classmethod function. This converts the method into a class method so that it accepts a class as its first parameter (i.e. Nhanvien).

In the last line, we call printTuoi without creating an object Nhanvien as in static method.

Running the above code, the program will return the result:

Số tuổi là: 25

When to use class methods?

1. Factory method

Factory method are methods that return an object of the class in different ways.

Like function overloading in C++, but Python doesn't have it, so here we use class methods and static methods.

Example 2: Create a factory method using class methods

from datetime import date

# random Nhanvien
class Nhanvien:
def __init__(self, ten, tuoi):
self.ten = ten
self.tuoi = tuoi

@classmethod
def 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 results:

Tuổi của Alice là: 23
Tuổi của Simon là: 28

Here we have two instance classes, one is created, the other is a class method fromBirthYear.

The instance created takes a name parameter (name) and age (age), fromBirthYear get information from class, name and birthYear then calculate the current age by subtracting the current year birthYear and returns the class instance result.

Method fromBirthYear receive information from class Nhanvien (Not object Nhanvien) as parameter cls and returns a function cls(name, date.today().year – birthYear) equivalent to Nhanvien(name, date.today().year – birthYear).
This is achieved thanks to decorator @classmethod. It is this decorator that transforms the method fromBirthYear of class method equals classmethod().

2. Create the correct instance in Inheritance.

Inheritance is reusing properties and functions of a class to define a new class. The newly created class is called a child class (child class or derived class), the inherited class is called a parent class (base class or parent class).

If you derive a class from creating a factory method using classmethod then it will definitely create the correct object in the child class.

You can also do the same but using staticmethod, the created object is definitely in the parent class.

Example 3: How class methods work in inheritance

from datetime import date

# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)

@classmethod
def 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 results:

True
False

This example uses a static method to create a class whose data type is hardwired during creation.

This causes a problem when inheriting Man from Person.

Method fromFathersAge does not return object in Man which returns the object at the class Person – parent class.

This violates the OOP paradigm. Use class methods fromBirthYear can ensure the OOP model of the code because it takes the first parameter which is the class itself which is passed in with its factory method.

See more:

Previous lesson: Chr() function in Python

Next lesson: Complex() function in Python

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments