Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass String Parameter into Class/Function (Python)

Tags:

python

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?

like image 505
MTG Avatar asked Jun 26 '26 20:06

MTG


2 Answers

You can parse and eval the string like:

Code:

@classmethod
def from_str(cls, a_str):
    return cls(**eval("dict({})".format(a_str)))

Test Code:

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)

Results:

100
like image 192
Stephen Rauch Avatar answered Jun 28 '26 09:06

Stephen Rauch


use eval

temp = eval("Sample("+my_str+")")
like image 32
Nozar Safari Avatar answered Jun 28 '26 10:06

Nozar Safari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!