3

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?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
MTG
  • 163
  • 2
  • 12

6 Answers6

4

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
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • How about `ast.literal_eval` instead? I guess formatting it to a dict is ok too. – pylang Feb 17 '18 at 05:55
  • @pylang [`ast.literal_eval`](https://docs.python.org/3/library/ast.html#ast.literal_eval) can't handle operators (like `=`). `ast.literal_eval('a=100')` raises `SyntaxError: invalid syntax`. – G_M Feb 17 '18 at 05:56
1

use eval

temp = eval("Sample("+my_str+")")
Nozar Safari
  • 505
  • 4
  • 17
1

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'>
G_M
  • 3,342
  • 1
  • 9
  • 23
0

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

CodeIt
  • 3,492
  • 3
  • 26
  • 37
0

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
CodeIt
  • 3,492
  • 3
  • 26
  • 37
Vikram Hosakote
  • 3,528
  • 12
  • 23
0

You can simply put temp = Sample(100,100,100) the class will automatically interpret

a = 100
b = 100
c= 100