i want to import some function in a class without needing to import the whole class.
I have some class as follows
class MyClass:
def __init__(self):
pass #Some init stuff
def some_funcs(self):
pass #Some other funcs
@staticmethod
def desired_func():
pass #The func i want to import
from MyClassFile import MyClass.desired_func
or
from MyClassFile.MyClass import desired_func
I tried to import that way but isn't work, is there any way to do it?
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.
With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math. sqrt(), but by using static import we can access sqrt() method directly.
To call a static method from another class, you use the name of the class followed by the method name, like this: ClassName. methodName().
To play devil's advocate:
# MyScript.py
desired_func = __import__('MyClassFile').MyClass.desired_func
On a more serious note, it sounds like your staticmethod
should actually just be a module level function. Python is not Java.
If you insist on having a staticmethod, pick one of the options below:
f = MyClass.desired_func
MyClassFile.py
, after the class definition block, alias a module-level function to the staticmethod and then import that name directly. 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