# Issue

This Content is from Stack Overflow. Question asked by Tichomír Duchaplný

I’m new to python and I wonder, if is possible to make a single method to manipulate with all class attributes, like:

``````class Test:
def __init__(self, dict1 = {"test": 0}, dict2 = {"another_test": 0}):
self.dict1= dict1
self.dict2 = dict2

def vary_attr(self, attr, key, value):
self.attr[key] += value

x = Test()
x.vary_attr('dict1', 'test', 3)
x.vary_attr('dict2', 'another_test', 6)

print(x.dict1)

# Wishful output:
# {'test': 3}
# {'another_test': 6}
``````

Obviously, this doesn’t work, but it is possible to make it work? Having one method and through that method manipulate with both attributes dict1 and dict2?!

# Solution

Actually your use case is to first get the attribute which is dictionary, then make the necessary updates. You can use `getattr` to get the attribute then perform necessary operations.

``````class Test:
def __init__(self, dict1 = {"test": 0}, dict2 = {"another_test": 0}):
self.dict1= dict1
self.dict2 = dict2

def vary_attr(self, attr, key, value):
# get class attribute by attribute name attr
_atr = getattr(self, attr)
_atr.update({key: _atr.get(key, 0)+value})

x = Test()
x.vary_attr('dict1', 'test', 3)
x.vary_attr('dict2', 'another_test', 6)
# x.dict1, x.dict2
# ({'test': 6}, {'another_test': 6})
``````

Note, your use case doesn’t require to set the attribute dynamically cause `dict.update` is a mutable function, but for other use cases, you can use `setattr` and pass `self`, `attr`, and `value` as parameters.

``` This Question was asked in  StackOverflow by  Tichomír Duchaplný and Answered by ThePyGuy It is licensed under the terms of
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.```
{"ft_lang_label":"__label__en","ft_lang_prob":0.6528827,"math_prob":0.72577035,"size":1662,"snap":"2023-14-2023-23","text_gpt3_token_len":484,"char_repetition_ratio":0.13027744,"word_repetition_ratio":0.184,"special_character_ratio":0.3026474,"punctuation_ratio":0.21937323,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.97082055,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-24T18:25:37Z\",\"WARC-Record-ID\":\"<urn:uuid:1a1cb4fe-3385-4119-96fb-0ce37e5c0035>\",\"Content-Length\":\"113691\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:b38dc384-6bcc-4f7b-8059-30eff1ff22ea>\",\"WARC-Concurrent-To\":\"<urn:uuid:86ff3dbb-f7bf-4ad4-abbc-a3fe806e995a>\",\"WARC-IP-Address\":\"195.179.239.8\",\"WARC-Target-URI\":\"https://jtuto.com/python-using-class-param-as-self/\",\"WARC-Payload-Digest\":\"sha1:ZHSCBSTSTFLZP2JMWYHB2XI4RWCU4T24\",\"WARC-Block-Digest\":\"sha1:7M35RX7MGN42RZWUMSMDDWEIRPSWNWZE\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296945288.47_warc_CC-MAIN-20230324180032-20230324210032-00177.warc.gz\"}"}