So I have a common module 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?. Common is a module consisting of a class 'common'.
We can also make class methods that can be called without having an instance. The method is then similar to a plain Python function, except that it is contained inside a class and the method name must be prefixed by the classname. Such methods are known as static methods.
Static method can be called without creating an object or instance. Simply create the method and call it directly. This is in a sense orthogonal to object orientated programming: we call a method without creating objects.
Class methods don't need self as an argument, but they do need a parameter called cls. This stands for class, and like self, gets automatically passed in by Python. Class methods are created using the @classmethod decorator.
To make a method as class method, add @classmethod decorator before the method definition, and add cls as the first parameter to the method. The @classmethod decorator is a built-in function decorator. In Python, we use the @classmethod decorator to declare a method as a class method.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With