[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 03:04:45 EDT 2017

On Sun, May 14, 2017 at 04:07:44AM +0000, Simon Ramstedt wrote:
> Hi, do you have an opinion on the following?

Hi, and welcome, and of course we have an opinion! This is Python-Ideas, 
we're very opinionated :-)

> Wouldn't it be nice to define classes via a simple constructor function (as
> below) instead of a conventional class definition?


> *conventional*:
>     class MyClass(ParentClass):
>       def __init__(x):
>         self._x = x
>       def my_method(y):
>         z = self._x + y
>         return z

Looks good to me. It is nicely explicit that you're creating a class, 
the superclass or superclasses are easy to see, and the attributes are 

> *proposed*:
>     def MyClass(x):

That is the exact same syntax for defining a function called "MyClass", 
that takes one argument, x. How is Python (and the reader!) supposed to 
tell which calls to def return a class and which return a function?

>       self = ParentClass()

What if you have multiple parent classes?

Why is self an instance of the parent class, instead of MyClass?

>       def my_method(y):
>         z = x + y
>         return z

The local variable x is not defined. Wait, is that supposed to come from 
the closure def MyClass(x)?

What if your class has twenty methods, each of which takes different 
arguments? Do you have to write:

def MyClass(x, # used in my_method
            y, # used in another_method
            z, # used in third_method,
            a, b, c, # used in fourth_method
            ...  # blah blah blah

How does this generalise to non-toy classes, classes with more than one 

>       self.my_method = my_method  # that's cumbersome (see comments below)
>       return self
> Here are the pros and cons I could come up with for the proposed method:
> (+) Simpler and more explicit.

I think you mean "More complicated and less explicit".

Is this supposed to be some sort of prototype-based OOP instead of 
class-based OOP? I'd be interested in investigating prototype-based 
objects, but I don't think this is the way to do it.


More information about the Python-ideas mailing list