Index
- built_in_functions
- Python abs()
- Python all()
- Python any()
- Python ascii()
- Python bin()
- Python bool()
- Python bytearray()
- Python bytes()
- Python callable()
- Python chr()
- Python classmethod()
- Python compile()
- Python complex()
- Python delattr()
- Python dict()
- Python dir()
- Python divmod()
- Python enumerate()
- Python eval()
- Python exec()
- Python filter()
- Python float()
- Python format()
- Python frozenset()
- Python getattr()
- Python globals()
- Python hasattr()
- Python hash()
- Python help()
- Python hex()
- Python id()
- Python input()
- Python int()
- Python isinstance()
- Python issubclass()
- Python iter()
- Python len()
- Python list()
- Python locals()
- Python map()
- Python max()
- Python memoryview()
- Python min()
- Python next()
- Python object()
- Python oct()
- Python open()
- Python ord()
- Python pow()
- Python print()
- Python property()
- Python range()
- Python repr()
- Python reversed()
- Python round()
- Python set()
- Python setattr()
- Python slice()
- Python sorted()
- Python staticmethod()
- Python str()
- Python sum()
- Python super()
- Python tuple() Function
- Python type()
- Python vars()
- Python zip()
- Python __import__()
- python1compute
- Python Program to Find Hash of File
- Python Program to Find the Size (Resolution) of a Image
- Python Program to Merge Mails
- Python Program to Count the Number of Each Vowel - Source Code: Using a list and a dictionary comprehension
- Python Program to Count the Number of Each Vowel - Source Code: Using Dictionary
- Python Program to Illustrate Different Set Operations
- Python Program to Sort Words in Alphabetic Order
- Python Program to Remove Punctuations From a String
- Python Program to Multiply Two Matrices - Matrix Multiplication Using Nested List Comprehension
- Python Program to Multiply Two Matrices - Source Code: Matrix Multiplication using Nested Loop
- Python Program to Transpose a Matrix - Matrix Transpose using Nested List Comprehension
- Python Program to Transpose a Matrix - Matrix Transpose using Nested Loop
- Python Program to Add Two Matrices - Source Code: Matrix Addition using Nested List Comprehension
- Python Program to Check Whether a String is Palindrome or Not
- Python Program to Add Two Matrices - Source code: Matrix Addition using Nested Loop
- Python Program to Convert Decimal to Binary Using Recursion
- Python Program to Find Factorial of Number Using Recursion
- Python Program to Find Sum of Natural Numbers Using Recursion
- Python Program to Display Fibonacci Sequence Using Recursion
- Python Program to Display Calendar
- Python Program to Shuffle Deck of Cards
- Python Program to Make a Simple Calculator
- Python Program to Find Factors of Number
- Python Program to Find LCM - Without using GCD function
- Python Program to Find HCF or GCD - Source Code: Using Euclidean Algorithm
- Python Program to Find LCM - Source Code: Using GCD function
- Python Program to Find HCF or GCD - Source Code: Using Loops
- Python Program to Find ASCII Value of Character
- Python Program to Convert Decimal to Binary, Octal and Hexadecimal
- Python Program to Find Numbers Divisible by Another Number
- Python Program To Display Powers of 2 Using Anonymous Function
- Python Program to Find the Sum of Natural Numbers
- Python Program to Find Armstrong Number in an Interval
- Python Program to Check Armstrong Number - Source Code: Check Armstrong number of n digits
- Python Program to Check Armstrong Number - Source Code: Check Armstrong number (for 3 digits)
- Python Program to Print the Fibonacci sequence
- Python Program to Display the multiplication Table
- Python Program to Find the Factorial of a Number
- Python Program to Print all Prime Numbers in an Interval
- Python Program to Find the Largest Among Three Numbers
- Python Program to Check Prime Number
- Python Program to Check Leap Year
- Python Program to Check if a Number is Odd or Even
- Python Program to Check if a Number is Positive, Negative or 0 Source Code: Using Nested if
- Python Program to Check if a Number is Positive, Negative or 0 Source Code: Using if...elif...else
- Python Program to Convert Celsius To Fahrenheit
- Python Program to Generate a Random Number
- Python Program to Convert Kilometers to Miles
- Python Program to Swap Two Variables Source Code: Without Using Temporary Variable
- Python Program to Swap Two Variables Source Code: Using temporary variable
- Python Program to Solve Quadratic Equation
- Python Program to Calculate the Area of a Triangle
- Python Program to Find the Square Root Source code: For real or complex numbers using cmath module
- Python Program to Find the Square Root Source Code: For positive numbers using exponent **
- Python Program to Add Two Numbers By One Line
- Python Program to Add Two Numbers Source Code: Add Two Numbers Provided by The User
- Python Program to Add Two Numbers
- Python Program to Print Hello world!
- python2based
Description classmethod()
Python classmethod()
The classmethod() method returns a class method for the given function.
The syntax of classmethod() method is:
classmethod(function)classmethod() is considered un-Pythonic so in newer Python versions, you can use the
@classmethod
decorator for classmethod definition.The syntax is:
@classmethod
def func(cls, args...)
classmethod() Parameters
The classmethod() method takes a single parameter:
• function - Function that needs to be converted into a class method
Return value from classmethod()
The classmethod() method returns a class method for the given function.
What is a class method?
A class method is a method that is bound to a class rather than its object. It doesn't require creation of a class instance, much like staticmethod.
The difference between a static method and a class method is:
• Static method knows nothing about the class and just deals with the parameters
• Class method works with the class since its parameter is always the class itself.
The class method can be called both by the class and its object.
Class.classmethod()
Or even
Class().classmethod()But no matter what, the class method is always attached to a class with first argument as the class itself cls.
def classMethod(cls, args...)
Example 1: Create class method using classmethod()
--------------------------------------------------------------------------
class Person:
age = 25
def printAge(cls):
print('The age is:', cls.age)
# create printAge class method
Person.printAge = classmethod(Person.printAge)
Person.printAge()
-----------------------------------------------------------------------------
When you run the program, the output will be:
The age is: 25
Here, we have a class
Person
, with a member variable age assigned to 25.We also have a function
printAge
which takes a single parameter cls and not self
we usually take.cls accepts the class
Person
as a parameter rather than Person's object/instance.Now, we pass the method
Person.printAge
as an argument to the function classmethod
. This converts the method to a class method so that it accepts the first parameter as a class (i.e. Person).In the final line, we call
printAge
without creating a Person object like we do for static methods. This prints the class variable age.When do you use class method?
1. Factory methods
Factory methods are those methods which return a class object (like constructor) for different use cases.
It is similar to function overloading in C++. Since, Python doesn't have anything as such, class methods and static methods are used.
Example 2: Create factory method using class method
-------------------------------------------------------------------------------------
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()
----------------------------------------------------------------------------------------
When you run the program, the output will be:
Adam's age is: 19
John's age is: 31
Here, we have two class instance creator, a constructor and a
fromBirthYear
method.Constructor takes normal parameters name and age. While,
fromBirthYear
takes class, nameand birthYear, calculates the current age by subtracting it with the current year and returns the class instance.The fromBirthYear method takes Person class (not Person object) as the first parameter clsand returns the constructor by calling
cls(name, date.today().year - birthYear)
, which is equivalent to Person(name, date.today().year - birthYear)
Before the method, we see
@classmethod
. This is called a decorator for converting fromBirthYear
to a class method as classmethod().2. Correct instance creation in inheritance
Whenever you derive a class from implementing a factory method as a class method, it ensures correct instance creation of the derived class.
You can create a static method for the above example but the object it creates, will always be hardcoded as Base class.
But, when you use a class method, it creates the correct instance of the derived class.
Example 3: How class method works for inheritance?
----------------------------------------------------------------------------------------------
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
@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))
class Man(Person):
sex = 'Male'
man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))
man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))
------------------------------------------------------------------------------------------------------
When you run the program, the output will be:
True
False
Here, using a static method to create a class instance wants us to hardcode the instance type during creation.
This clearly causes a problem when inheriting
Person
to Man
.fromFathersAge
method doesn't return a Man
object but its base class Person
's object.This violates OOP paradigm. Using a class method as
fromBirthYear
can ensure the OOP-ness of the code since it takes the first parameter as the class itself and calls its factory method.