It’s often the case that I write a class, along with helper functions that are intimately connected to that class. For my current, a Window class to wrap some win32api calls, along with functions to, say, find windows. Should those helper functions be globals in the given module, or should they be class methods of the Window class. That is, should I have, in my module:
class Window(object):
def __init__(self, handle):
self.handle = handle
...
...
@classmethod
def find_windows(cls, params):
handles = ...
return map(cls, handles)
with the usage being:
from window import Window
windows = Window.find_windows("Specialty")
or should I do:
class Window(object):
def __init__(self, handle):
self.handle = handle
...
...
def find_windows(params):
handles = ...
return map(Window, handles)
with the usage being:
from window import Window, find_windows
windows = find_windows("Speciality")
Put more succinctly: should the grouping be at the class-level (e.g. they would be static methods in Java) or at the module level?
The first approach has the advantage that in case you subclass
Windowyou can override yourfind_windowsmethod (unlike static methods in java). However, this would only be useful if overriding would eventually make sense, otherwise I think it looks nicer having it as a function.Edit: If you have multiple ways of finding Window objects, it would make sense to have an additonal class called WindowFinder or WindowManager which encapsulates query/finding logic.
This is a pattern used in django where if your Window class is let’s say a db model, you than have Window.objects pointing to a WindowManager. The window manager has methods for building sql queries.
Then, you can do things like:
or