0

Sometimes, I try to use a variable to name a function:

myVar = "something"

def myVar () :
    pass

The function thus created is not something() but myVar().

Same problem with global:

myVar = "something"

global myVar

In this example, the variable isn't something but it's myVar.

Actually, my problem is similar; I want to create an attribute from a variable:

class myClass :

    def __init__ (self) :
        myVar = "something"
        self.myVar = 1

Without surprise the attribute create in this example is self.myVar, not self.something.

Generally I try to avoid these kinds of problems by rethinking my code. But I would like to know if there is a way to do it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Morgan
  • 589
  • 9
  • 20
  • See also e.g. http://stackoverflow.com/q/285061/3001761 – jonrsharpe Apr 29 '15 at 10:05
  • Thanks jonrsharpe. I found the solution in stackoverflow.com/q/285061/3001761. Use setattr (self, myVar, 1) instead of self.myVar = 1 work perfectly. – Morgan Apr 29 '15 at 10:16
  • @Morgan Be sure to read the comments of https://stackoverflow.com/questions/1373164, e.g. "It's more than a "bad" thing. It's perfectly horrifying.". Instead it's better to rethink your code and avoid it (as you already stated). – syntonym Apr 29 '15 at 10:43
  • thanks syntonym, I saw this comment. – Morgan Apr 29 '15 at 11:38

0 Answers0