Re:Javascript-Style Objects in Python
by wbkang on Monday March 16, 2015 @01:24PM
(#9212847)
I thought this was something implemented using metaclasses to not have to use dictionary-style field access... (e.g., obj.field instead of obj['field'] )
[ Parent
| on HN ]
I don't think you need to use metaclasses, you can just define the relevant magic methods, something like:
class JSLikeObject(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
ETA: That gets you JavaScript-style equivalence between attribute and index lookup, but it doesn't get you JavaScript-like binding of "this". I think you could probably do that with descriptors (and maybe it would require writing a metaclass).
Re:Javascript-Style Objects in Python
by icebraining on Monday March 16, 2015 @01:49PM
(#9213013)