簡體   English   中英

如何在實例方法中訪問 static 變量

[英]How to access static variable inside instance method

因此,當我的 post 方法被點擊時,我正在使用 GenericAPIView function 被調用並執行某些操作,例如在我的 class 中創建和完成一些對象。 所以我在這里使用 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)

未解析的參考變量

變量var是一個局部變量。 它在您的my_custom_method static 方法中是本地的。 如果您想從其他方法訪問它,則需要將其聲明為 class(靜態)變量。

這是您的代碼的修改版本:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM