I wish to make a relatively fleeting object in Python. In Javascript, which has a similar internal semantic for object management (a lookup table) you can do the following:
/* Hopefully I'm not so out of practice with JS that this would cause an error: */
var not_a_defined_class;
not_a_defined_class.this_property_exists_as_of_this_line = 1
In Python, you cannot. The equivalent would be something like the following:
not_a_defined_class = object()
not_a_defined_class.__dict__['this_property_exists_as_of_this_line'] = 1
Evidently, dot-notation to access a member of a class is syntactic sugar:
class DefinedClass(object):
__init(self):
self.predefined_property = 2
defined_object = DefinedClass()
defined_object.predefined_property = 5
# Is syntactic sugar for:
defined_object.__dict__['predefined_property'] = 5
# But is read-only
defined_object.undefined_property = 6 # AttributeError
My questions then are as follows:
- Is there a difference between
.__dict__['predefined_property'] = 5and.predefined_property = 5? - Is dot-notation read-only outside class definitions (i.e. other than
self.new_property =)? (As far as I can tell this is the case) - If so, why? Type safety?
- Is there a way I can work around this? Is there a method called by dot-notation that I can recklessly override in my own class, say
MessyObject?
Of course, I could use a dictionary object to similar effect. I'm really asking this question to learn more.