简体   繁体   中英

Pass String Parameter into Class/Function (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?

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

使用eval

temp = eval("Sample("+my_str+")")

Although it is definitely an option, using eval can be dangerous . Here is an option which is @StephenRauch 's code just without using eval .

>>> class Sample:
...     def __init__(self, a, b, c):
...         self.a = a
...         self.b = b
...         self.c = c
... 
...     @classmethod
...     def from_str(cls, a_str):
...         result = {}
...         for kv in a_str.split(','):
...             k, v = kv.split('=')
...             result[k] = int(v)
...         return cls(**result)
... 
>>> x = Sample.from_str('a=100,b=100,c=100')
>>> x.a
100
>>> type(x.a)
<class 'int'>

You can use the below code.

class Sample:
    def __init__(self, a, b, c):
        self.a = int(a)
        self.b = int(b)
        self.c = int(c)

mystr = "a=100,b=100,c=100"
temp = Sample(mystr.split(",")[0].split("=")[1],mystr.split(",")[1].split("=")[1],mystr.split(",")[2].split("=")[1])
print(temp.a)
print(temp.b)
print(temp.c)

See it in action here

This works for me:

my_str = "a=100,b=100,c=100"                                                                                         

temp = Sample(int(my_str.split(',')[0].split('=')[1]),
               int(my_str.split(',')[1].split('=')[1]),
               int(my_str.split(',')[2].split('=')[1]))

print(temp.a)
# prints 100

print(temp.b)
# prints 100

print(temp.c)
# prints 100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM