Python Class Method Decorator @classmethod
In Python, the @classmetho
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.
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)
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
.
Comments
Post a Comment
If you have any doubts, Please let me know