(based on something I read on LinkedIn)
Everybody "knows" that Python objects have dynamic attributes.
Well - turn out that reality is that Python objects *by default* have dynamic attributes and that the features can be disabled on a per class basis, which can improve both memory usage and execution speed.
Demo:
C:\Work\Python>type dynattr.py
class X:
def __init__(self, a, b):
self.a = a
self.b = b
o = X(123, 'ABC')
print(o.__dict__)
print('%d %s' % (o.a, o.b))
o.c = 456
o.d = 'DEF'
print(o.__dict__)
print('%d %s %d %s' % (o.a, o.b, o.c, o.d))
C:\Work\Python>python dynattr.py
{'a': 123, 'b': 'ABC'}
123 ABC
{'a': 123, 'b': 'ABC', 'c': 456, 'd': 'DEF'}
123 ABC 456 DEF
C:\Work\Python>type nodynattr.py
class X:
__slots__ = [ 'a', 'b' ]
def __init__(self, a, b):
self.a = a
self.b = b
o = X(123, 'ABC')
try:
print(o.__dict__)
except Exception as ex:
print(str(ex))
print('%d %s' % (o.a, o.b))
try:
o.c = 456
o.d = 'DEF'
except Exception as ex:
print(str(ex))
try:
print(o.__dict__)
except Exception as ex:
print(str(ex))
try:
print('%d %s %d %s' % (o.a, o.b, o.c, o.d))
except Exception as ex:
print(str(ex))
C:\Work\Python>python nodynattr.py
'X' object has no attribute '__dict__'
123 ABC
'X' object has no attribute 'c'
'X' object has no attribute '__dict__'
'X' object has no attribute 'c'