Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a class with all static methods [closed]

I have a python Class with all methods being static,

class SomeClass:

    @staticmethod
    def somemethod(...):
       pass

    @staticmethod
    def somemethod2(...):
       pass

    @staticmethod
    def somemethod3(...):
       pass

Is it the right way to do so?

like image 368
Grizzled Squirrel Avatar asked Dec 07 '22 19:12

Grizzled Squirrel


2 Answers

If all the methods are static, you DON'T need a class.

(Same if you have a class with only an init and 1 method)

someclass.py

class SomeClass:

    @staticmethod
    def somemethod(...):
        pass

    @staticmethod
    def somemethod2(...):
        pass

    @staticmethod
    def somemethod3(...):
        pass

Then you use it mostly like:

from someclass import SomeClass
some_class = SomeClass()
some_class.somemethod()
....

I always refactor such class into simple methods

someclass.py

def somemethod(...):
    pass

def somemethod2(...):
    pass

def somemethod3(...):
    pass

then I use it this way:

import someclass
someclass.somemethod()
...

Isn't this cleaner and simpler?

Extra info

class SomeClass:

    foo = 1

    def __init__(self, bar):
        self.bar = bar
        self.foo = 2

    @staticmethod
    def somemethod():
        # no access to self nor cls but can read foo via SomeClass.foo (1)
        foo = SomeClass.foo
        SomeClass.someclassmethod()
        ...

    @classmethod
    def someclassmethod(cls, ...):
        # access to cls, cls.foo (always 1), no access to bar
        foo = cls.foo
        ...

    def someinstancemethod(self, ...):
        # access to self, self.bar, self.foo (2 instead of 1 because of init)
        foo = self.foo
        bar = self.bar
        self.somemethod()
        self.someclassmethod()
        ...
like image 123
DevLounge Avatar answered Dec 11 '22 11:12

DevLounge


Described case is too general to give the exact recipe. Relying on just your sample regular functions looks better here rather than decorator's and class complexity.

def somemethod():
   pass

def somemethod2():
   pass

def somemethod3():
   pass
like image 37
koxt Avatar answered Dec 11 '22 12:12

koxt