Python – Is it possible to import class method without instantiating class


Having class located somewhere in

I can access his method like this

from .my_module import Mailer

mailer = Mailer()

But if I can import just do_stuff method from class? If so, can I import not only static methods?

Best Solution

You can access class and static methods on the class, without creating an instance. For example, take the following demo class:

class Demo(object):

    def instance_method(self):
        print "Called an instance method"

    def class_method(cls):
        print "Called a class method"

    def static_method():
        print "Called a static method"

Now we can call two of those methods directly on the class:

>>> Demo.class_method()
Called a class method
>>> Demo.static_method()
Called a static method

But we can't call the instance method, as we don't have an instance for the self argument:

>>> Demo.instance_method()

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Demo instance as first argument (got nothing instead)

You can call all three types of method on an instance:

>>> instance = Demo()
>>> instance.class_method()
Called a class method
>>> instance.static_method()
Called a static method
>>> instance.instance_method()
Called an instance method

Note that static methods don't use any class or instance attributes, therefore they are pretty much identical to functions. If you find yourself wanting to call a function without referencing the class or an instance, just factor it out to a function.