Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class with only class methods

I have a class with only class methods. Is it a Pythonic way of namespacing? If not, what is the best way to group similar kinds of methods?.

class OnlyClassMethods(object):
    @classmethod
    def method_1(cls):
        pass

    @classmethod
    def method_2(cls):
        pass
like image 814
Sijeesh Avatar asked Feb 12 '19 21:02

Sijeesh


People also ask

Can a class only have methods?

Action Class: class that contains only methods, and no fields.

How do you use class methods in Python?

To make a method as class method, add @classmethod decorator before the method definition, and add cls as the first parameter to the method. The @classmethod decorator is a built-in function decorator. In Python, we use the @classmethod decorator to declare a method as a class method.

Is class method defined inside a class?

A class method is a method that 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.

What is the difference between Classmethod and Staticmethod?

The class method takes cls (class) as first argument. The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state.


1 Answers

A class is meant to have instances, not to serve as namespace. If your class is never instantiated, it does not serve the intended purpose of Python's class.

If you want to namespace a group of methods which are related, create a new module, that is another .py file, and import it.

Example

Here we create a module named helpers which contains some related methods. This module can then be imported in our main file.

helpers.py

def method_1():
    ...

def method_2():
    ...

main.py

import helpers

helpers.method_1()
helpers.method_2()
like image 199
Olivier Melançon Avatar answered Sep 22 '22 16:09

Olivier Melançon