Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to import class method without instantiating class?

Having class located somewhere in my_module.py

I can access his method like this

from .my_module import Mailer

mailer = Mailer()
mailer.do_stuff()

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

like image 481
micgeronimo Avatar asked Feb 12 '15 09:02

micgeronimo


People also ask

Can static methods be called without instantiating the class first?

In the same way that a static variable is associated with the class as a whole, so is a static method. In the same way that a static variable exists before an object of the class is instantiated, a static method can be called before instantiating an object.

Can you call the class method without creating an instance?

Static method(s) are associated with the class in which they reside i.e. they are called without creating an instance of the class i.e ClassName. methodName(args). They are designed with the aim to be shared among all objects created from the same class.

Can you call the base class method without creating an instance in CPP?

Answer: Yes,It is possible, 1) If it is a static method.


1 Answers

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"

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

    @staticmethod
    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>
    Demo.instance_method()
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.

like image 78
jonrsharpe Avatar answered Oct 03 '22 18:10

jonrsharpe