Home > database >  How to assign parameter value to self?
How to assign parameter value to self?

Time:11-30

Is it possible to assign a function parameter into self directly?

The code below is an example of what I'd like to achieve.

class SomeClass:
    def some_function(self, key)
        self.<key> = 1

I managed something similar for a param keyword using:

**{key: val}

But can't work out how to do something similar for self

CodePudding user response:

You can use setattr and pass the key as a string

class SomeClass:
    def some_function(self, key, value):
        setattr(self, key, value)
  • Related