Top 10 Advance Java Interview questions? What are the differences between abstract classes and interfaces in Java? What is the difference between ArrayList and LinkedList in Java? What is the purpose of the finalize() method in Java? What is polymorphism in Java and how is it achieved? What are the different types of inner classes in Java? What is the difference between static and non-static methods in Java? What are the different types of exceptions in Java and how do they differ? What is the difference between checked and unchecked exceptions in Java? How does Java handle multithreading and synchronization? What are the different types of JDBC drivers in Java and how do they differ?
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