Search code examples
python-2.7categorization

Python categorize functions


Is there any way to Categorize Functions so that I could call a function like this:

category something():
    def test():
        [Code]

    def test2():
        [Code]

something.test()
something.test2()

I thought of using classes, but it seems like they always need an instance e.g. self as an attribute.

If I'm wrong please feel free to correct me, I am kind of new to python and don't have that much experience.

For now, I've been using different files for that but I often ran into circular dependency issues and wanted to ask if there's an easy solution to this problem.

This is for cleaning up the code a bit and to know to which part of a scipt a function may belong when you have lots of code.


Solution

  • You don't actually need an instance - you can declare each method as (or, actually, transform it into) a "static" method:

    class Foo:
    
        @staticmethod 
        def Bar(x, y):
            return x + y
    
        @staticmethod 
        def Baz(x, y):
            return x - y
    
    print(Foo.Bar(3, 4))
    

    The interpretation of the first argument as a reference to the instance (conventionally, but not necessarily, called self) does not happen in static methods.

    But creating classes full of static methods would be a somewhat off-label use of class. The more common way to categorize resources in Python is to divide them into modules and packages (i.e. separate files and/or directories):

    # in Foo.py
    def Bar(x, y):
        return x + y
    

    and then:

    >>> import Foo
    >>> Foo.Bar(3, 4)
    7