Python classmethod() Built in Function

The Python classmethod() function is a built-in function that returns a class method for a given function. A class method is a method that is bound to a class rather than an instance of the class. It can access and modify class variables and can be called by both instances and classes.

One use case of class methods is to create factory methods that can create objects of different subclasses based on some parameters. Another use case is to access or modify class variables without creating an instance.

Here are some examples of using the classmethod() function:


# Example 1: Define a class method using @classmethod decorator
class Person:
    age = 25

    @classmethod
    def printAge(cls):
        print('The age is:', cls.age)

Person.printAge()
# The age is: 25

# Example 2: Define a factory method using @classmethod decorator
class Animal:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_species(cls, species):
        if species == 'dog':
            return cls('Rover')
        elif species == 'cat':
            return cls('Fluffy')
        else:
            return cls('Unknown')


dog = Animal.from_species('dog')
print(dog.name)
# Rover

cat = Animal.from_species('cat')
print(cat.name)
# Fluffy

bird = Animal.from_species('bird')
print(bird.name)
# Unknown

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions