ScanSkill

classmethod

This classmethod() function returns a class method for the function.

Syntax

classmethod(class)

Here,

  • class: Required. Name of the class.

Note: When classmethod is called, it gets the class as the first argument instead of the instance of that class (as we normally do with methods). This means we can use the class and its properties inside that method rather than a particular instance.

Examples

>>> #This example shows obsolete syntax
>>> #Note that method bar can be called on both class and instance objects
>>> class Class1:
...     def func1(cls):             #
...         print 'hello’           #
...     bar = classmethod(bar)    #<= not pythonic anymore, decorator syntax recommended
...
>>> Class1.func1
<bound method classobj.func1 of <class __main__.Class1 at 0x00CDAC00>>
>>> Func1.func1()
hello
>>> Class1().func1
<bound method classobj.func1 of <class __main__.Class1 at 0x00CDAC00>>
>>> Class1().func1()
hello
  • Without decorator
>>> from datetime import date

# random Person
>>> class Person:
...    def __init__(self, name, age):
...        self.name = name
...        self.age = age
...
...    @classmethod
...    def fromBirthYear(cls, name, birthYear):
...        return cls(name, date.today().year - birthYear)
...
...    def display(self):
...        print(self.name + "'s age is: " + str(self.age))
...
>>> person = Person('Adam', 19)
>>> person.display()

>>> person1 = Person.fromBirthYear('John',  1985)
>>> person1.display()
Adam's age is: 19
John's age is: 31

here, a constructor takes parameters name and age. While the method fromBirthYear takes class, name, and birthyear and calculates age then returns the class instance.