+ 6
is there any way to create a variable from a command in python? Example: x = while, x(True):
5 odpowiedzi
+ 11
thanks! :)
+ 10
I tried to do this, but I did not quite understand how to set the command to the variable, could you explain me better? Sorry, I'm still starting to study in-depth programming.
+ 6
As far as I know, you are limited. You could:
x="while (y < 3):\n print(y)\n y+=1"
y=0
exec(x)
which would output 0, 1, and 2.
+ 2
Let me ask you back.
You want to, as the result of a method's execution, instantiate a variable at runtime, or assign a value to an existing variable based on some method's return value?
If it's the first case, my previous answer addresses your problem.
"self." variables are global variables, meaning that they will exist during the entire class existence and can be accessed by any of its class' methods. Variables declared without "self." prefix only exist inside the scope they belong to (a loop, an if-else, etc.), being destroyed as soon as the scope ends.
Understand "self" as "a class variable that is a property of itself" and, like so, ia accessible anywhere in the class.
Hope that this explanation helps a little more!
+ 1
Haven't tried yet, but I came up with a suggestion that might work.
Try creating a method that defines the variable as a global, with "self". See below.
def criaVariavel(self, k):
if k == True:
self.x = k
And then you could test if self.x was created, by using try/except.
try:
a = self.x
'''if the variable exists, this assignment is possible. If doesn't,, python raises an exception and goes to the next block.'''
except:
a = 2
Worth a try!