繁体   English   中英

将字符串参数传递给类/函数(Python)

[英]Pass String Parameter into Class/Function (Python)

如果我有这样的课程:

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

我可以通过以下方式创建对象:

temp = Sample(a=100,b=100,c=100)

但是,如果我有:

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

我怎么能temp = Sample(my_str)正确?

您可以像这样解析和评估字符串:

码:

@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

使用eval

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

尽管绝对是一种选择,但使用eval可能很危险 这是一个@StephenRauch的代码,只是不使用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'>

您可以使用以下代码。

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)

看到它在这里行动

这对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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