[Python-ideas] JavaScript-Style Object Creation in Python (using a constructor function instead of a class to create objects)

Steven D'Aprano steve at pearwood.info
Sun May 14 07:48:52 EDT 2017

On Sun, May 14, 2017 at 01:33:32PM +0200, Antoine Rozo wrote:
> Also, how do you handle special methods for operators, such as __add__?

Oh, that's a good point! I forgot about that.

For implementation-dependent reasons, you couldn't use this proposed new 
syntax for dunder methods:

def MyClass():
    self = subclass(Parent)

    def my_method(arg):
    self.my_method = my_method

    def __str__():
    self.__str__ = __str__

    return self

obj = MyClass()
obj.my_method(123)  # okay
obj.__str__()  # works, but bad style
str(obj)  # doesn't work in CPython

Because of the implementation, str(obj) would NOT call __str__ in 
CPython, although I think it would in IronPython. I'm not sure about 
PyPy or Jython.

(CPython "new style classes" only call __dunder__ methods when they are 
defined on the class, or a superclass, not when they are in the instance 


More information about the Python-ideas mailing list