Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python using class param as self

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?!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading