pythonmethodsmodule

How do I use a class method without passing an instance to it?


I have a common module which consists of a class common which contains processing functions for numbers and types of data I am using. I want to be able to include it like from common import common (or better yet just import common) and use functions like common.howLongAgo(unixTimeStamp).

What is required to do this in my common module?


Solution

  • Ways of exposing methods in a python module:

    module foo.py:

    def module_method():
        return "I am a module method"
    
    class ModClass:
         @staticmethod
         def static_method():
             # the static method gets passed nothing
             return "I am a static method"
         @classmethod
         def class_method(cls):
             # the class method gets passed the class (in this case ModCLass)
             return "I am a class method"
         def instance_method(self):
             # An instance method gets passed the instance of ModClass
             return "I am an instance method"
    

    now, importing:

    >>> import foo
    >>> foo.module_method()
    'I am a module method'
    >>> foo.ModClass.static_method()
    'I am a static method'
    >>> foo.ModClass.class_method()
    'I am a class method'
    >>> instance = ModClass()
    >>> instance.instance_method()
    'I am an instance method'
    

    If you want to make class method more useful, import the class directly:

    >>> from foo import ModClass
    >>> ModClass.class_method()
    'I am a class method'
    

    You can also import ... as ... to make it more readable:

    >>> from foo import ModClass as Foo
    >>> Foo.class_method()
    'I am a class method'
    

    Which ones you should use is somewhat a matter of taste. My personal rule of thumb is: