Your request to set a new variable is odd, and probably not the right solution to whatever problem you're trying to solve.
That being said, you can use setattr to set the value based on the name of a variable. That variable doesn't have to exist. For example, to set the variable self.edition
to 1
you can do setattr(self, "edition", 1)
.
Therefore, you can pass in the string name of the variable to your whichButton
function, and use setattr
to set a variable with that name.
It would look something like this:
def whichButton(self, _var, _pressedButton):
setattr(self, _var, _pressedButton)
...
self.checkScooter = Button(..., command=lambda: self.whichButton("edition", 1))
...
self.checkAbonnement = Button(..., command=lambda: self.whichButton("abonnement", 3))
In the above code, clicking either button will either set self.edition
or self.abonnement
.
There is almost certainly a better solution to your problem, but your question doesn't provide any details about what problem you're really trying to solve. A simple mprovement over this would be to use a dictionary to hold your "new" variables rather than creating literally new variables.
You can do that by defining a dictionary in your __init__
and then setting it in your whichButton
function.
It would look something like this:
class Something:
def __init__(self):
self._vars = {}
def whichButton(self, name, new_value):
self._vars[name] = new_value
This has the advantage that all of these special variables exist in a single data structure, separate from the object. That means that it would be impossible to accidentally overwrite instance variables.