Barka
Barka

Reputation: 8922

Modifying a class attribute from an instance

I have the following code:

Class X(Parent):
   ...
Class Y(Parent):
   ...
Class Z(Parent):
  ...

X._dict = {'a':1, 'b':2, 'c':3}
Y._dict = {'e':4, 'f':5, 'g':6}
Z._dict = {'k':7, 'l':8, 'm':9}

def add_to_dict(obj, k, v):
   obj._dict [k] = v

I want to call add_to_dict(), passing it an object of type X, Y, or Z. add_to_dict() should then add the k, v key-value pair to the class's _dict (not the instance's)

The last line above:

obj._dict [k] = v

adds the key-value pair to the object's _dict attribute. I need to fix it so the key-value pair is instead added to the class _dict attribute. How do I do this?

Note: I do not have access to the Parent class.

Upvotes: 2

Views: 61

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

Use type() to access the class of the instance like:

Code:

def add_to_dict(obj, k, v):
    type(obj)._dict[k] = v

Test Code:

class X(object):
    pass

X._dict = {'a': 1, 'b': 2, 'c': 3}

a = X()
b = X()

add_to_dict(a, 'z', 20)
print(a._dict)
print(b._dict)
print(X._dict)

Results:

{'a': 1, 'b': 2, 'c': 3, 'z': 20}
{'a': 1, 'b': 2, 'c': 3, 'z': 20}
{'a': 1, 'b': 2, 'c': 3, 'z': 20}

Upvotes: 4

Related Questions