[英]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.