Home > Blockchain >  How to access static variable inside instance method
How to access static variable inside instance method

Time:09-03

So i am using a GenericAPIView when my post method is hit function gets called and perform certain action like creating and completing some objects in my class. so i am using a static method here but in exception i am not being able to refer to variable named var used in static method to use in my post method exception

class MyApiView(GenericAPIView):

    @staticmethod
    def my_custom_method(arg):
        if condition1 and condition2:
           var = Class1(arg=arg)
           var.create()
        
           var = Class2(arg=arg)
           var.complete()
         
        if condition4 or condition3:
           var = Class3(arg=arg)
           var.create()
        
     def post(self, request):
         try:
            my_cust_method(arg)
         except Exception:
            logger.error(f"{var.__class__}", exc_info=True)

Unresolved reference var

CodePudding user response:

The variable var is a local variable. It is local to your my_custom_method static method. If you would like to access it from other methods then you will need to declare it as a class (static) variable.

Here is a modified version of your code:

class MyApiView(GenericAPIView):

    var = None

    @staticmethod
    def my_custom_method(arg):
        if condition1 and condition2:
           MyApiView.var = Class1(arg=arg)
           MyApiView.var.create()
        
           MyApiView.var = Class2(arg=arg)
           MyApiView.var.complete()
         
        if condition4 or condition3:
           MyApiView.var = Class3(arg=arg)
           MyApiView.var.create()
        
     def post(self, request):
         try:
            my_cust_method(arg)
         except Exception:
            if MyApiView.var == None:
                logger.error(f"var not initialised", exc_info=True)
            else:
                logger.error(f"{MyApiView.var.__class__}", exc_info=True)
  • Related