Grouping Functions by Using Classes in Python

后端 未结 3 1544
小蘑菇
小蘑菇 2021-02-01 16:14

I have been a Python Scientific Programmer for a few years now, and I find myself coming to a sort specific problem as my programs get larger and larger. I am self taught so I h

3条回答
  •  难免孤独
    2021-02-01 16:59

    I wouldn't use a class for this, I'd use a module. A class consisting of only staticmethods strikes me as a code smell too. Here's how to do it with modules: any time you stick code in a separate file and import it into another file, Python sticks that code in a module with the same name as the file. So in your case:

    In mathutil.py

    def add(a,b):
        return a+b
    
    def sub(a,b):
        return a-b
    

    In main.py

    import mathutil
    
    def main():
        c = mathutil.add(a,b)
    

    Or, if you're going to use mathutil in a lot of places and don't want to type out (and read) the full module name each time, come up with a standard abbreviation and use that everywhere:

    In main.py, alternate version

    import mathutil as mu
    
    def main():
        c = mu.add(a,b)
    

    Compared to your method you'll have more files with fewer functions in each of them, but I think it's easier to navigate your code that way.

    By the way, there is a bit of a Python convention for naming files/modules: short names, all lower case, without underscores between words. It's not what I started out doing, but I've moved over to doing it that way in my code and it's made it easier to understand the structure of other people's modules that I've used.

提交回复
热议问题