Skip to content

Instantly share code, notes, and snippets.

@hygull
Last active September 23, 2019 17:09
Show Gist options
  • Save hygull/eb0259f9fa9050ece66e4723c3729efc to your computer and use it in GitHub Desktop.
Save hygull/eb0259f9fa9050ece66e4723c3729efc to your computer and use it in GitHub Desktop.
Use of setattr() function to set attributes of class object

setattr()

Check my answer at https://stackoverflow.com/a/58067032/6615163

>>> class TEST:
...     def __init__(self, project = 'ABC', scenarios = {'A': [1,2,3], 'B': [4,5,6]}):
...         self.project = project
...         for feature in scenarios:
...             scenario = scenarios[feature]
...             setattr(self, feature, scenario)
... 
>>> 
>>> P = TEST(project = 'ABC', scenarios = {'A': [1,2,3], 'B': [4,5,6], 'C': [7,8,9]})
>>> 
>>> P.A
[1, 2, 3]
>>> 
>>> P.B
[4, 5, 6]
>>> 
>>> P.C
[7, 8, 9]
>>> 
>>> class A:
...     pass
... 
>>> a = A()
>>> setattr(a, "prop1", 10)
>>> 
>>> a.prop1
10
>>> 
>>> setattr(a, "increment", lambda x: x + 1)
>>> 
>>> a.increment(110)
111
>>> 

Help on built-in function setattr in module builtins:

setattr(obj, name, value, /) Sets the named attribute on the given object to the specified value.

setattr(x, 'y', v) is equivalent to ``x.y = v''

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment