Andriy Kravchenko Andriy Kravchenko - 7 months ago 14
Python Question

Refer to defined variable from function outside Python class

Excuse for newbie question but I want make all clear for myself. I have a problem accessing class variable from within function outside the class. In code below I need

text, text2
. I get variables as tuple but I need them separately. How to update code to get defined variable like
text = var1
and
text2 = var2
? Thanks in advance!

from django.shortcuts import render

class Someclass():
def method_1(self):
self.var2 = 'var2'
self.var1 = 'var1'
return self.var1 ,self.var2

def func(request):
cls = Someclass()
text2 = cls.method_1()
text = cls.method_1()
content = {
'text': text,
'text2': text2,
}
return render(request, "web/page.html", content)

Answer

Use tuple unpacking - you can return several results, and receive several results from a func

text, text2 = cls.method_1()

Also you better not name your variables text and text2. And also cls is a common word to use for a class, and in your code cls is an instance, that's a bit unpythonic :)