class method vs static method in python

Python Methods and Functions

Decorator @classmethod — it is a built-in

# Python program for demonstration
# using class method and static method.

from datetime import date

 

class Person:

def __ init __ ( self , name, age):

self . name = < code class = "plain"> name

self . age = age

  

# class method for creating a Person object by year of birth.

@ classmethod

def fromBirthYear ( cls , name, year):

return cls (name, date.today (). year - year )

 

# static method to check if the Person is an adult or not.

@staticmethod

  def isAdult (age):

return age & gt;  18

 

person1 = Person ( ' mayank' , 21 )

person2 = Person.fromBirthYear ( ' mayank' , 1996 )

 

print person1.age

print person2.age

  
# print the result

print Person. isAdult ( 22 )

Exit

 21 21 True 

This article courtesy of Mayank Agrawal . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.