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?
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.
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.
Answer: Yes,It is possible, 1) If it is a static method.
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.
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