Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python Class Method Decorator @classmethod

In Python, the @classmethod decorator is used to declare a method in the class as a class method that can be called using ClassName.MethodName(). The class method can also be called using an object of the class.

The @classmethod is an alternative of the classmethod() function. It is recommended to use the @classmethod decorator instead of the function because it is just a syntactic sugar.

@classmethod Characteristics

  • Declares a class method.
  • The first parameter must be cls, which can be used to access class attributes.
  • The class method can only access the class attributes but not the instance attributes.
  • The class method can be called using ClassName.MethodName() and also using object.
  • It can return an object of the class.

The following example declares a class method.

Example: @classmethod
class Student:
    name = 'unknown' # class attribute
    def __init__(self):
        self.age = 20  # instance attribute

    @classmethod
    def tostring(cls):
        print('Student Class Attributes: name=',cls.name)

Student.tostring()  #Student Class Attributes: name=unknown
Try it

Above, the Student class contains a class attribute name and an instance attribute age. The tostring() method is decorated with the @classmethod decorator that makes it a class method, which can be called using the Student.tostring(). You can call the class method as classname.method() or using class object object.method().

Note: The first parameter of any class method must be cls that can be used to access the class's attributes. You can give any name to the first parameter instead of cls.

The class method can only access class attributes, but not the instance attributes. It will raise an error if trying to access the instance attribute in the class method.

Example: @classmethod
class Student:
    name = 'unknown' # class attribute
    def __init__(self):
        self.age = 20  # instance attribute

    @classmethod
    def tostring(cls):
        print('Student Class Attributes: name=',cls.name,', age=', cls.age)


Student.tostring() #calling class method
Try it

The class method can also be used as a factory method to get an object of the class, as shown below.

Example: @classmethod
class Student:
    def __init__(self, name, age):
        self.name = name  # instance attribute
        self.age = age # instance attribute

    @classmethod
    def getobject(cls):
        return cls('Steve', 25)


std = Student.getobject()
print(std.name)  #'Steve'    
print(std.age)   #25
Try it

@classmethod vs @staticmethod

The following table lists the difference between the class method and the static method:

@classmethod@staticmethod
Declares a class method.Declares a static method.
It can access class attributes, but not the instance attributes.It cannot access either class attributes or instance attributes.
It can be called using the ClassName.MethodName() or object.MethodName().It can be called using the ClassName.MethodName() or object.MethodName().
It can be used to declare a factory method that returns objects of the class.It cannot return an object of the class.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.