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
Action Class: class that contains only methods, and no fields.
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.
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.
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.
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.
Here we create a module named helpers
which contains some related methods. This module can then be imported in our main
file.
def method_1():
...
def method_2():
...
import helpers
helpers.method_1()
helpers.method_2()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With