Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import static method of a class without importing the whole class [duplicate]

i want to import some function in a class without needing to import the whole class.

I have some class as follows


MyClassFile.py

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

MyScript.py

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?

like image 481
Ivan Gonzalez Avatar asked Jan 09 '18 23:01

Ivan Gonzalez


People also ask

Can you import a static method?

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.

How do you call a static method from another class without using an instance?

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.

How do you import static members of a class?

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.

How do you call a static method from another class in Java?

To call a static method from another class, you use the name of the class followed by the method name, like this: ClassName. methodName().


1 Answers

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:

  1. Import the class as usual and then bind a local function: f = MyClass.desired_func
  2. In MyClassFile.py, after the class definition block, alias a module-level function to the staticmethod and then import that name directly.
like image 143
2 revs Avatar answered Sep 29 '22 10:09

2 revs