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?

5
  • 3
    This seems like an XY problem. Where do you get that string? Commented Feb 17, 2018 at 5:47
  • you might need to parse it in another constructor Commented Feb 17, 2018 at 5:50
  • propose : change __init__ to `__init__(self , **kwds) Commented Feb 17, 2018 at 6:37
  • 1
    Some of these answers are recommending to use eval. While it is simple, there are reasons why eval is discouraged. Commented Feb 17, 2018 at 9:43
  • eval is a to use , no for avoiding! it has proplems but when need must use it , Commented Feb 17, 2018 at 12:44

6 Answers 6

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
Sign up to request clarification or add additional context in comments.

2 Comments

How about ast.literal_eval instead? I guess formatting it to a dict is ok too.
@pylang ast.literal_eval can't handle operators (like =). ast.literal_eval('a=100') raises SyntaxError: invalid syntax.
1

use eval

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

Comments

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'>

Comments

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

3 Comments

I don't understand the negative voting for my answer.
me too, yours and below ones same I guess - imma upvote you buddy
@AnkushRathi Thanks.
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

3 Comments

Shouldn't temp.a == 100 and not temp.a == 'a=100'?
But isn't it supposed to be an integer? You are returning '100' vs 100
@DeliriousLettuce Thanks for the comment, edited it again :) How does it look now?
0

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

a = 100
b = 100
c= 100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.