Re:Javascript-Style Objects in Python
by icebraining on Monday March 16, 2015 @01:44PM
(#9212976)
You could do that by creating an object that encapsulates the dictionary, defines a __call__ method, and repasses the method calls to the underlying dictionary.
That's what a Python object is... The underlying dictionary is called __dict__.
Re:Javascript-Style Objects in Python
by AnkhMorporkian on Monday March 16, 2015 @02:19PM
(#9213223)
Static methods are fantastic. I use them all the time for deserialization. Adding a .from_json() static method to create a new instance makes way more sense to me than putting one outside the class.
- For the dot syntax, all you have to do is define the __call__ method. You could do that by creating an object that encapsulates the dictionary, defines a __call__ method, and repasses the method calls to the underlying dictionary.
- For inheritance, just create another constructor function that calls the parent constructor, adds the desired methods, and returns the new function. In JavaScript, it's called parasithic inheritance.
- For the iteration method, you just have to define the __iter__ method.
- For the isinstance and issubclass method, maybe you could create new conventions (and thus reinvent the wheel)
- About static method... should we be using them anyway?
Those are just some thoughts. This alternative way of creating objects is probably useless, nevertheless fun.