Movatterモバイル変換


[0]ホーム

URL:


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

Simon Ramstedtsimonramstedt at gmail.com
Sun May 14 00:07:44 EDT 2017


Hi, do you have an opinion on the following?Wouldn't it be nice to define classes via a simple constructor function (asbelow) 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*proposed*:    def MyClass(x):      self = ParentClass()      def my_method(y):        z = x + y        return z      self.my_method = my_method  # that's cumbersome (see comments below)      return selfHere are the pros and cons I could come up with for the proposed method:(+) Simpler and more explicit.(+) No need to create attributes (like `self._x`) just to pass somethingfrom `__init__` to another method.(+) Default arguments / annotations for methods could be different for eachclass instance. Adaptive defaults wouldn't have to simulated with a None.(+) Class/instance level imports would work.(-/+) Speed: The `def`-based objects take 0.6 μs to create while the`class`-based objects take only 0.4 μs. For method execution however theclosure takes only 0.15 μs while the proper method takes 0.22 μs (script<https://gist.github.com/rmst/78b2b0f56a3d9ec13b1ec6f3bd50aa9c>).(-/+) Checking types: In the proposed example above the returned objectwouldn't know that it has been created by `MyClass`. There are a couple ofsolutions to that, though. The easiest to implement would be to change thefirst line to `self = subclass(ParentClass())` where the subclass functionlooks at the next item in the call stack (i.e. `MyClass`) and makes it thetype of the object. Another solution would be to have a special rule forfunctions with capital first letter returning a single object to appenditself to the list of types of the returned object. Alternatively therecould be a special keyword e.g. `classdef` that would be used instead of`def` if we wouldn't want to rely on the name.(-) The current syntax for adding a function to an object is cumbersome.That's what is preventing me from actually using the proposed pattern. Butis this really the only reason for not using it? And if so, wouldn't thatbe a good argument for enabling something like below?*attribute function definitions*:    def MyClass(x):      self = ParentClass()      def self.my_method(y):        z = x + y        return z      return selfor alternatively *multiline lambdas*:    def MyClass(x):      self = ParentClass()      self.my_method = (y):        z = x + y        return z      return selfCheers,Simon-------------- next part --------------An HTML attachment was scrubbed...URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170514/5d0da83e/attachment-0001.html>


More information about the Python-ideasmailing list

[8]ページ先頭

©2009-2025 Movatter.jp