Python Class Method Decorator @classmethod

@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.
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(). Note that 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store