In Python how do I use a class method without passing an instance to it?
Solution 1
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:
- Simple utility functions that generally act on things like collections, or perform some computation or fetch some resource should be module methods
- Functions related to a class but that do not require either a class or an instance should be static methods
- Functions that are related to a class, and will need the class for comparison, or to access class variable should be class methods.
- Functions that will act on an instance should be instance method.
Solution 2
if you have module common.py and function is in class common
class common(object):
def howLongAgo(self,timestamp):
some_code
then you should change your method to be static method whit decorator @staticmethod
class common(object):
@staticmethod
def howLongAgo(timestamp): # self goes out
some_code
This way you do not need to change whole class and you can still use self.howLongAgo in class
Comments
-
user3607601 about 4 years
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 justimport common
) and use functions likecommon.howLongAgo(unixTimeStamp)
What is required to do this in my common module?. Common is a module consisting of a class 'common'.