J
J
Jan2020-07-30 21:36:39
Python
Jan, 2020-07-30 21:36:39

"Why doesn't {this code} work?" or “How do I create a method that will create any method?” in Python?

Hello colleagues.
The question is not practical, just curious.

Here I was trying to turn the argument into an attribute.
Why is this code not working? ↓

class ClassName:
    def add(self, **kwargs):
        for key, value in kwargs.items():
            eval(f'self.{key} = {value}')

exemplar = ClassName()
exemplar.add(name = 'Python')
print(exemplar.name)

# File "<string>", line 1
#     self.name = Python
#               ^
# SyntaxError: invalid syntax

Tried to change the key string but that doesn't work either:
class ClassName:
    def add(self, **kwargs):
        for key, value in kwargs.items():
            eval(f'self.{key} = "{value}"')

exemplar = ClassName()
exemplar.add(name = 'Python')
print(exemplar.name)

# File "<string>", line 1
#     self.name = "Python"
#               ^
# SyntaxError: invalid syntax


The first question is:
____ How can I make a magic method
____ that will turn any attributes into arguments?

The second one is more interesting:
____ How to make a magic method
____ that will turn an array of arguments into new methods?

Horror, how interesting!
Thanks for any tips ;)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-07-30
@JanJarius

eval(f'self.{key} = "{value}"')this is a perversion, you just need tosetattr(self, key, value)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question