On 01/09/2018 07:30 AM, Steven D'Aprano wrote:
> If you have a class with only data, and you access the attributes via the 
> instance's __dict__, why not use an ordinary dict?

Or even subclass dict.

class MyClass(dict):
  VAR = 5

m = MyClass()
m['newvar'] = "Something"

I do this and wrap things like __getitem__, __call__, __del__, etc. with
my own methods.  For example...

def __getitem__(self, key):
  # return self.attribute if given "_attribute_" mapping
  if key[0] == '_' and key[-1] == '_' and key[1] != '_':
    k = key[1:-1]
    if hasattr(self, k): return getattr(self, k)
  return dict.__getitem__(self, key)

So, in the above example...

>>>print("newvar = '%(newvar)s', VAR = '%(_VAR_)s'" % m
newvar = 'Something', VAR = '5'

-- 
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:da...@vex.net VoIP: sip:da...@vybenetworks.com
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to