简体   繁体   English

如何在基于django类的视图中从同一个类中的另一个方法访问一个方法的变量

[英]how to access variable of one method from another method within the same class in django class based views

I need to access the value of method variable from another method in django class based views. 我需要从基于django类的视图中的另一个方法访问方法变量的值。 I have defined a variable as none in class variable. 我在类变量中将变量定义为none。 I have created two method inside the django class as like below 我在django类中创建了两个方法,如下所示

 class XXXXX(UpdateView):
    y = None

    def get_context_data(self,**kwargs):
        y = 10
        return super(xxxxx,self).get_context_data(**kwargs)

    def post(self,request,*args,**kwargs):
        # Here i want to access the value of variable y which is in get_context_data method
        # i have tried to access like **self.y**. But am getting the value as **None**

Can anyone help me to find what mistake i did 谁能帮我找到我犯的错误

The reason is that get_context_data is called after post . 原因是get_context_data post 之后被调用。 When post runs, y hasn't been set yet. post ,尚未设置y

You shouldn't be overriding post anyway. 无论如何,您都不应覆盖post You haven't stated what you need to do with that variable, but there is certainly a more appropriate method to override. 您尚未说明需要使用该变量做什么,但是肯定有更合适的方法可以覆盖。

Also, note that just assigning to y inside a method doesn't have any effect outside that method: you need to assign to self.y . 另外,请注意,仅在方法内部分配给y对该方法外部没有任何影响:您需要分配给self.y And the class-level assignment is pointless, you should remove it. 而且,类级别的分配是没有意义的,您应该将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在同一个类中从一个方法访问我的变量? - how to access my variable from one method to another in same class? 如何从同一个类中的另一个方法访问一个类中的方法中的变量 - How to access a variable in a method in a class from another method in the same class 如何从同一类中的另一个方法访问方法变量(Tkinter)? - How to access a method variable (Tkinter) from another method in same class? 如何在同一个类中从一种方法访问列表到另一种方法 - How to access the list from one method to another in the same class Django - 在基于类的视图中从另一个方法调用一个类方法 - Django - Calling one class method from another in Class Based View 在 Python 中的同一类中从另一个方法调用一个方法 - Calling one method from another within same class in Python 如何在Python中从一个类访问类方法和类变量到另一个类的实例方法? - How to access class method and class variable from a class to another class's instance method in Python? 从Django模型方法访问类变量 - access class variable from django model method 从同一类中的另一个方法调用变量 - Calling a variable from another method in the same class 如何从同一 class 中的静态方法访问 class 中的 python 方法 - how to access a python method within a class from a staticmethod within the same class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM