I am an advanced programmer who recently started using and learning python. I recently ran into this question. The answers in that question suggests that instead of using a static method inside a class, it is considered better design to just use a method and not use a class at all.
Code design 1:
gameResolution.py
width = 300
height = 300
# other variables, and functions following...
screenResolution.py
width = 1920
height = 1080
# other variables and functions following...
Code design 2:
resolution.py
class GameResolution:
width = 300
height = 300
# static functions following
class ScreenResolution:
width = 1920
height = 1080
# static functions following
As you can probably see, Code design 2 makes a lot more sense (in my opinion) in this situation. I could pack anything related to that entity (GameResolution or ScreenResolution for example) inside a class and all those classes inside a resolution.py file.
If I followed the Code design 1 I would end up with many tiny .py files, that would each represent a very small class. Correct ?
So, is it actually true that static methods are a bad approach for python ? In this situation, what would you do ?
1 Answer 1
The best solution depends on your style a bit. That being said, I don't think making classes that as a single use static are the way to go. I would do one of the following:
- Make a class that handles all the resolution stuff (GameResolution/ScreenResolution/etc) and make separate instances of it for each.
- Change the names of
widthandheighttogame_width,game_height,screen_widthandscreen_height.
As for when I use static methods, about the only time is for creating objects in a way different then the initializer for some reason. The need to do such is fairly rare though. It definitely sounds like your use case is better suited to either one class to represent everything, or if they're different enough then globals and functions instead of classes and static methods.
1 Comment
Resolution class. So my example with the resolutions was a pretty bad example. However as you say globals and functions instead of classes and static methods is what everyone seems to be using and you also say it is the way to go, so it has to be
widthandheightthe object attributes, and the methods non-static. Then you can create multipleGameResolutions etc.# other variables, and functions following...that do no match, so making aResolutionclass is not really possible. However since they do share a couple of common features it makes sense to keep them inside a common fileresolution.pyin my opinion, instead of making a douzen small.pyfiles