oop - Appropriate way to group static functions in python -


what appropriate way group static functions in python?

considerations:

  1. functions in same group not need share state or information.
  2. there several groups each containing 3 functions, sharing common "interface".

it seems solution creating class each group. has advantage of providing interface subclassing abstract class. less messy creating separate modules groups. however, makes no sense instantiate these classes - should static classes.

any ideas best way of designing this? should add @staticmethod each method in each class or there more elegant way of doing (e.g. declaring whole class static)?

edit: since question tagged "opinion-based", ask more concretely: there anyway declare whole class static?

is there anyway declare whole class static?

you can use metaclass achieve this. way can intercept class-creation , replace methods static methods.

from types import functiontype   class staticmetaclass(type):     def __new__(cls, name, bases, dct):         def transform(f):             if type(f) == functiontype:                 return staticmethod(f)             return f          newdct = dict((k, transform(v)) k, v in dct.iteritems())          return type.__new__(cls, name, bases, newdct)   class staticbase(object):     __metaclass__ = staticmetaclass   class static(staticbase):     def func1():         print "func1"      def func2(a, b):         print "func2", a, b   static.func1() static.func2(1, "world") 

[...] there more elegant way of doing [...] ?

i leave question, whether more elegant, you. however, usage of metaclasses discouraged, if avoidable. tend make code bases more complicated , confusing. also, many programmers not familiar them. so, code become harder maintain.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -