[英]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.