If I have a class as such:
class Sample:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
I can create an object by:
temp = Sample(a=100,b=100,c=100)
But what if I have:
my_str = "a=100,b=100,c=100"
How can I temp = Sample(my_str) properly?
You can parse and eval the string like:
@classmethod
def from_str(cls, a_str):
return cls(**eval("dict({})".format(a_str)))
class Sample:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
@classmethod
def from_str(cls, a_str):
return cls(**eval("dict({})".format(a_str)))
x = Sample.from_str("a=100,b=100,c=100")
print(x.a)
100
use eval
temp = eval("Sample("+my_str+")")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With