Converts a given function into a class method.
classmethod() to create the
Codecademy class method:
class Student:name = "Codecademy"def print_name(obj):print("Welcome to...", obj.name)Student.print_name = classmethod(Student.print_name)Student.print_name()
Here’s an example to illustrate the usage of
Output for the above code is:
Instance method called by Object 1Class method called. Total instances created: 2Class method called. Total instances created: 2Class method called. Total instances created: 2
In the above example, a class called
MyClass is defined with a class attribute
count and two methods:
instance_method is a regular instance method that can access instance-specific attributes. It is called using an instance of the class.
class_method is a class method decorated with
classmethod(). It takes the class itself (
cls) as the first parameter instead of the instance (
self). It can access and modify class-level attributes, such as
count. It can be called using the class name or an instance of the class.
- Anonymous contributorAnonymous contributor194 total contributions
- dakshdeepHERE23 total contributions
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions