1

I have the following code:

tmpVariable = completeVariableName[filedsValueCounter];
tmpValue = fieldsValue[fieldsName[fieldsNameCounter]];
print eval ("'%s = \"%s\";' % (tmpVariable, tmpValue)");

Output of above code is :

self.name = "Peter"

Next line of eval function is :

print self.name

But It's output is :

None

Question: Where's my problem?

0

3 Answers 3

2

For executing statements (such as the assignment in the question) in Python, you must use exec() because eval() works only for expressions (things that evaluate to values). Anyway, you don't need to evaluate the string in this case, setattr is the way to go:

setattr(self, 'name', 'Peter')

The above piece of code will have the same effect that this one:

self.name = 'Peter'
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I need to retrive my variable name from a list.So i need to exec or eval functions.
I convert my eval function to exec ('%s = \"%s\"' % (tmpVariable, tmpValue)); and got good answer. Thank you.
1

eval is for expressions, but assignment is a statement.

However there is no need to use it here. You should use setattr.

Comments

1

what if instead you wanted to create instances of a class using the replacement.

something like this:

class Class1:
    pass
class Class2:
    def generateParameters(self):
        self.parameters = ['a', 'b', 'c']
        for i in parameters:
        "self.{0} = class2()".format(i)

the idea being to generate a number of instances with specific varaibles

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.