Python: classmethod() function
The classmethod() function is used to convert a method into a class method.
A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator. It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
|function||Function that needs to be converted into a class method||Required|
Return a class method for function.
Example: Create class method using classmethod()
class Example: age = 55 def printAge(cls): print('The age is:', cls.age) # create printAge class method Example.printAge = classmethod(Example.printAge) Example.printAge()
The age is: 55
Python Code Editor:
Test your Python skills with w3resource's quiz
Python: Tips of the Day
How do I check if a list is empty?
For example, if passed the following:
a =  if not a: print("List is empty")
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework