[Python-ideas] JavaScript-Style Object Creation in Python (using a constructor function instead of a class to create objects)
Ivan Levkivskyi
levkivskyi at gmail.com
Wed May 17 12:48:25 EDT 2017
On 17 May 2017 at 18:38, Stephan Houben <stephanh42 at gmail.com> wrote:
> Hi Sven,
>
> > But even given that (and I am only speaking for my team), I haven't even
> > seen a use-case for namedtuples in a year. Every time we considered it,
> > people said: "please make it its own class for documentary purposes; this
> > thing will tend to grow faster than we can imagine".
>
> Using namedtuple doesn't stop the class from being its "own class".
> Typical use case:
>
> class Foo(namedtuple("Foo", "bar "baz"), FooBase):
> "Foo is a very important class and you should totally use it."""
>
> def grand_total(self):
> return self.bar + self.baz
>
And the right (modern) way to do this is
from typing import NamedTuple
class Foo(NamedTuple):
"""Foo is a very important class and
you should totally use it.
"""
bar: int
baz: int = 0
def grand_total(self):
return self.bar + self.baz
typing.NamedTuple supports docstrings, user-defined methods, and default
values.
--
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170517/6bb4b09a/attachment.html>
More information about the Python-ideas
mailing list