Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's an example use case for a Python classmethod?

I've read What are Class methods in Python for? but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python.

Can you name a small, specific example use case where a Python classmethod would be the right tool for the job?

like image 601
coffee-grinder Avatar asked Apr 21 '11 01:04

coffee-grinder


People also ask

What is the use of Classmethod in Python?

A class method is a method which is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class.

When should I use Classmethod Python?

You can use class methods for any methods that are not bound to a specific instance but the class. In practice, you often use class methods for methods that create an instance of the class. When a method creates an instance of the class and returns it, the method is called a factory method.

Where is Classmethod Python used?

In Python, the @classmethod decorator is used to declare a method in the class as a class method that can be called using ClassName. MethodName() . The class method can also be called using an object of the class. The @classmethod is an alternative of the classmethod() function.

What is the purpose of Classmethod and Staticmethod in Python?

The difference between the Class method and the static method is: A class method takes cls as the first parameter while a static method needs no specific parameters. A class method can access or modify the class state while a static method can't access or modify it.


1 Answers

Helper methods for initialization:

class MyStream(object):      @classmethod     def from_file(cls, filepath, ignore_comments=False):             with open(filepath, 'r') as fileobj:             for obj in cls(fileobj, ignore_comments):                 yield obj      @classmethod     def from_socket(cls, socket, ignore_comments=False):         raise NotImplemented # Placeholder until implemented      def __init__(self, iterable, ignore_comments=False):        ... 
like image 103
anijhaw Avatar answered Oct 04 '22 07:10

anijhaw