'How can I call a static method from a class variable? It gives an error while importing in another notebook

I have 2 files: file1 and file2 in the same directory:

Contents of file1:

class Class1:
   class_variable = widgets.interactive_output(Class1.static_method, {'index' : index})

   @staticmethod
   def static_method(index):
       //body of the function

Contents of file2:

from file1 import Class1

When i run file2, I get following errors based on calls:

When I call it using:
1. Class1.static_method, {'index' : index})
   I get the error:
   NameError: name 'Class1' is not defined

2. static_method, {'index' : index})
   I get the error:
   NameError: name 'static_method' is not defined

How can I solve this? Any help is appreciated..



Solution 1:[1]

Not sure how you plan to use Class1 in your code, but indeed the issue is that Class1 is not defined at the point when you reference it. You can use a classmethod to define a class attribute.

file1.py

class Class1:
    @staticmethod
    def static_method(index):
        //body of the function
        
    def __new__(cls, *args, **kwargs):
        cls.class_variable = widgets.interactive_output(cls.static_method, {'index' : index})
        return super(Class1, cls).__new__(cls)

Here I'm using __new__ as class method as it runs automatically at the instantiation of the class, but you can define your own.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 arabinelli