Converting Python strings to variable names

Asked 2 years ago, Updated 2 years ago, 60 views

Hello. ^^

I was making a program "Self the string delivered as a factor.Can we replace it with a variable?" I'm asking this question because I'm

For example, this is the case.

def a(self, string) :
    self.string = {
    ~~~~~~~~
    }

a('hello')

It's a very omitted content, but the intention is whether you can variable the argument you delivered.

After passing the string 'hello' to the string with a('hello'), insert it into the string position Finally, can you name the variable self.hello?

I wonder if this is possible inside Python.

Thank you all for your interest in the question, and I look forward to hearing from you soon. Thank you ^^

python string variable

2022-09-20 16:22

2 Answers

There's a way to get rid of it, but don't make such a strong move.


2022-09-20 16:22

It's a question that's already been adopted, but the answer seems strange, so I'm writing.

You can use setattr.

class Dynamic:
    def set_attribute(self, string):
        setattr(self, string, {"hello": "world"})


d = Dynamic()
d.set_attribute("hello")
print(d.hello)  # {'hello': 'world'}

d.set_attribute("world")
print(d.world)  # {'hello': 'world'}


2022-09-20 16:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.