Just out of curiosity I'm playing with the __dict__
attribute on Python classes.
I read somewhere that a "class" in python is kind of a dict, and calling __dict__
on a class instance translate the instance into a dict... and I thought "cool! I can use this!"
But this lead me to doubts about the correctness and security of these actions.
For example, if I do:
class fooclass(object):
def __init__(self, arg):
self.arg1 = arg
p = fooclass('value1')
print(p.__dict__)
p.__dict__['arg2'] = 'value2'
print(p.__dict__)
print(p.arg2)
I have this:
>>>{'arg1': 'value1'}
>>>{'arg1': 'value1', 'arg2': 'value2'}
>>>value2
and that's fine, but:
- Does the
fooclass
still have 1 attribute? How can I be sure? - Is it secure to add attributes that way?
- Have you ever had cases where this came in handy?
- I see that I can't do
fooclass.__dict__['arg2'] = 'value2'
.. so why this difference between a class and an instance?