'How do I convert string to object type without using eval() in for loop?
class Testclass:
def change(self, obj):
if(self.ball):
self.ball=False
obj.ball=True
main():
A=Testclass()
B=Testclass()
seq=["AB", "BA", "AB"]
for val in seq:
obj1, obj2=list(val) #to split "AB" into A, B
eval(obj1).change(eval(obj2))
.change() method changes object's boolean value to the other object's value. Just for the test.
How can I avoid using eval in this loop? Without eval(), following error appears: 'str' object has no attribute 'change'
I'm using python 3.10
Solution 1:[1]
One option would be to use tuples instead of strings:
A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for val in seq:
obj1, obj2=list(val) #to split "AB" into A, B
obj1.change(obj2)
Or, combining the unpacking directly with the for loop:
A = Testclass()
B = Testclass()
seq=[(A, B), (B, A), (A, B)]
for obj1, obj2 in seq:
obj1.change(obj2)
Generally speaking, you'd only use strings if you need to write and read the data to and from a file (or a database or some other external system) or for display on the screen; while it's inside the program, keep things as objects (or numbers etc), don't convert back and forth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ji?í Baum |
