[英]How to access static variable inside instance method
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.因此,当我的 post 方法被点击时,我正在使用 GenericAPIView function 被调用并执行某些操作,例如在我的 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
所以我在这里使用 static 方法,但在异常情况下,我无法引用 static 方法中使用的名为var的变量以在我的 post 方法异常中使用
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未解析的参考变量
The variable var
is a local variable.变量
var
是一个局部变量。 It is local to your my_custom_method
static method.它在您的
my_custom_method
static 方法中是本地的。 If you would like to access it from other methods then you will need to declare it as a class (static) variable.如果您想从其他方法访问它,则需要将其声明为 class(静态)变量。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.