Home > Backend Development > Python Tutorial > What's the Difference Between `@classmethod` and `@staticmethod` in Python?

What's the Difference Between `@classmethod` and `@staticmethod` in Python?

Barbara Streisand
Release: 2024-12-22 10:16:46
Original
294 people have browsed it

What's the Difference Between `@classmethod` and `@staticmethod` in Python?

Meaning and Usage of @classmethod and @staticmethod for Beginners

In Python, @classmethod and @staticmethod are decorators used to define methods with specific characteristics.

@classmethod

A classmethod is a method that is bound to a class, not to an individual instance of the class. It must have a class as its first argument, which is typically named cls. By convention, classmethods are named with from_ or create_ prefixes.

When to use @classmethod:

  • When you want to create a factory method that returns a new instance of the class.
  • When you want to define a method that operates on the class itself, rather than on an instance.

Example:

class Date:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return cls(day, month, year)
Copy after login

@staticmethod

A staticmethod is a method that is not bound to either the class or an instance. It does not have access to any instance or class variables. Staticmethods are typically used for utility functions that can be reused without modification.

When to use @staticmethod:

  • When you want to define a function that performs some operation but does not depend on the class or instance state.
  • When you want to create a function that can be called from any context.

Example:

class Date:
    @staticmethod
    def is_date_valid(date_as_string):
        day, month, year = map(int, date_as_string.split('-'))
        return day <= 31 and month <= 12 and year <= 3999
Copy after login

Difference between @classmethod and @staticmethod

Feature @classmethod @staticmethod
Access to class Has access to the class No access to the class
Access to instance No access to instances No access to instances
Usage Factory methods, operations on the class Utility functions, independent of class or instances

The above is the detailed content of What's the Difference Between `@classmethod` and `@staticmethod` in Python?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template