Rocksolid Light

Welcome to novaBBS (click a section below)

mail  files  register  newsreader  groups  login

Message-ID:  

There's no future in time travel.


devel / comp.lang.python / an oop question

SubjectAuthor
* an oop questionJulieta Shem
+* Re: an oop questionStefan Ram
|`* Re: an oop questionJulieta Shem
| +* Re: an oop questionJulieta Shem
| |`* Re: an oop questionChris Angelico
| | `* Re: an oop questionJulieta Shem
| |  `* Re: an oop questionChris Angelico
| |   `* Re: an oop questionJulieta Shem
| |    `* Re: an oop questionStefan Ram
| |     +- Re: an oop questionWeatherby,Gerard
| |     `* Re: an oop questionJulieta Shem
| |      +* Re: an oop questionGreg Ewing
| |      |+* Re: an oop questionStefan Ram
| |      ||`- Re: an oop questionJulieta Shem
| |      |`* Re: an oop questionJulieta Shem
| |      | `* Re: an oop questionGreg Ewing
| |      |  `* Re: an oop questionJulieta Shem
| |      |   `* Re: an oop questionGreg Ewing
| |      |    `- Re: an oop questionJulieta Shem
| |      `- Re: an oop questionStefan Ram
| `* Re: an oop questionGiorgio Pastore
|  `* Re: an oop questionStefan Ram
|   `- Re: an oop questiondn
+* Re: an oop questionWeatherby,Gerard
|+- Re: an oop questionStefan Ram
|`- Re: an oop questionStefan Ram
`* Re: an oop questionAlan Gauld
 `* Re: an oop questionJulieta Shem
  +* Re: an oop questionStefan Ram
  |+* Re: an oop questionStefan Ram
  ||`* Re: an oop questionJulieta Shem
  || `* Re: an oop questionStefan Ram
  ||  `* Re: [correction]an oop questionStefan Ram
  ||   `* Re: [correction]an oop questionDennis Lee Bieber
  ||    +* Re: [correction]an oop questionAlan Gauld
  ||    |`- Re: an oop questionStefan Ram
  ||    `- Re: [correction]an oop questionJulieta Shem
  |`* Re: an oop questionJulieta Shem
  | +* Re: an oop questionStefan Ram
  | |`- Re: an oop questionJulieta Shem
  | +* Re: an oop questionStefan Ram
  | |`- Re: an oop questionJulieta Shem
  | +* Re: an oop questionAlan Gauld
  | |`- Re: an oop questionStefan Ram
  | +- Re: an oop questionWeatherby,Gerard
  | `* Re: an oop questionChris Angelico
  |  +* Re: an oop questionJulieta Shem
  |  |+- Re: an oop questionChris Angelico
  |  |`- Re: an oop questionAlan Gauld
  |  +- Re: an oop questionWeatherby,Gerard
  |  `* Re: an oop questionGreg Ewing
  |   `* Re: an oop questionChris Angelico
  |    `- Re: an oop questionGreg Ewing
  `* Re: an oop questionAlan Gauld
   `* Re: an oop questionJulieta Shem
    `* Re: an oop questionStefan Ram
     `* Re: an oop questionJulieta Shem
      +* Re: an oop questionGreg Ewing
      |`- Re: an oop questionChris Angelico
      +- Re: an oop questionGreg Ewing
      `* Re: an oop questionStefan Ram
       `- Re: an oop questionJulieta Shem

Pages:123
an oop question

<86y1sxmmvo.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20097&group=comp.lang.python#20097

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.nntp4.net!aioe.org!KiP7B6UDtf9WpJXNvjWpEg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: an oop question
Date: Sun, 30 Oct 2022 11:01:15 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86y1sxmmvo.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="19146"; posting-host="KiP7B6UDtf9WpJXNvjWpEg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
Cancel-Lock: sha1:N66ad3vU8YZ4cjMVYfMYEvv2j5U=
X-Notice: Filtered by postfilter v. 0.9.2
 by: Julieta Shem - Sun, 30 Oct 2022 14:01 UTC

I have a question about a particular case I'm working on. I'm studying
OOP. To ask the question, I'm going to have to introduce you my context
here, so you'll need to bear with me. If you'd like to see the question
right away, go to the section ``My difficulty in encapsulating a
union''.

(*) Introduction

I wrote the classes

class Empty:
...
class Pair:
...

With them, I can (sort of) make a union of them and build a Lisp-like
list by defining that my Lisp-like list is either Empty or a Pair. For
instance, here's a Lisp-like sequence that represents the string "abc".

>>> Pair.fromIterable("abc")
Pair('a', Pair('b', Pair('c', Empty())))

So far so good. (``Full'' code at the end of this message, if you'd
like to more carefully look into my reasoning there.)

(*) How to build a stack?

These Lisp-like sequences are clearly a stack. You pop an element from
it by grabbing the first element. You push an element on to it by just
pairing the new element with the current stack. For instance, let's pop
the 1-string "a" off of the stack.

>>> ls = Pair.fromIterable("abc")
>>> ls.first
'a'
>>> ls = ls.rest
>>> ls
Pair('b', Pair('c', Empty()))

Done. Let's push it back on.

>>> ls = Pair("a", ls)
>>> ls
Pair('a', Pair('b', Pair('c', Empty())))

So far so good, but when it comes to building a better user interface
for it I have no idea how to do it. I think one of the purposes of OOP
is to organize code hierarchically so that we can reuse what we wrote.
So I tried to make a Stack by inheriting Pair.

class Stack(Pair):
pass

>>> Stack(1, Empty())
Stack(1, Empty())

Then I wrote pop and push.

>>> Stack(1, Empty()).pop()
1

>>> Stack(1, Empty()).push(2)
Stack(2, Stack(1, Empty()))

So far so good. Now let me show you what I can't do.

(*) The difficulty of encapsulating a union

The Lisp-like sequences we're building here are union-like data
structures. A /sequence/ is either Empty() or Pair(..., /sequence/). I
have not found a way to represent this either-or datastructure with a
class. For example, there is no way right now to build an empty Stack
by invoking the Stack constructor.

>>> Stack()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Pair.__init__() missing 2 required positional arguments: 'first' and 'rest'

As I designed, an empty Stack is represented by Empty(), which is a
whole other object. Users will have to know this. I wish I did not
have to burden my users with such knowledge. For instance, I wish the
answer was "Stack()" to the question of -- ``how can I build an empty
stack?''

My desire seems to imply that I need a union-like data structure. If
Stack is invoked with no arguments, it should produce Empty(), otherwise
it produces Pair() as it does today.

How can I achieve that?

(*) Code

class Pair:
def __init__(self, first, rest):
if not isinstance(rest, Pair) and not isinstance(rest, Empty):
raise ValueError("rest must be Empty or Pair")
self.first = first
self.rest = rest
def fromIterable(it):
if len(it) == 0:
return Empty()
else:
return Pair(it[0], Pair.fromIterable(it[1:]))
def __str__(self):
return "{}({!r}, {})".format(self.__class__.__name__, self.first, str(self.rest))
def __repr__(self):
return str(self)
def __len__(self):
return 1 + self.rest.__len__()

class Empty:
def __len__(self):
return 0
def __str__(self):
return "Empty()"
def __repr__(self):
return self.__str__()
def __new__(clss):
if not hasattr(clss, "saved"):
clss.saved = super().__new__(clss)
return clss.saved

class Stack(Pair):
def pop(self):
return self.first
def push(self, x):
return Stack(x, self)

Re: an oop question

<unions-20221030153013@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20098&group=comp.lang.python#20098

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 30 Oct 2022 14:31:01 GMT
Organization: Stefan Ram
Lines: 24
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <unions-20221030153013@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de a5nfn7mV+Vt/GJS51j2SZQJT5ng5Yh/37gyExyOlYzKGH0
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Sun, 30 Oct 2022 14:31 UTC

Julieta Shem <jshem@yaxenu.org> writes:
>My desire seems to imply that I need a union-like data structure.

You only need to worry about such things in languages with
static typing. For example, to have a function that can
sometimes return an int value and at other times a string
value in C, one would need a union.

In Python with its dynamic typing, one does not need unions.

def an_int_sometimes_and_sometimes_a_string( x ):
if x:
return 2
else:
return "two"

a_name_for_an_int_sometimes_and_sometimes_string = 2
a_name_for_an_int_sometimes_and_sometimes_string = "abc"

. If you should, however, be talking about the new "type hints":
These are static and have "Union", for example, "Union[int, str]"
or "int | str".

Re: an oop question

<86k04hmkf3.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20099&group=comp.lang.python#20099

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!KiP7B6UDtf9WpJXNvjWpEg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Sun, 30 Oct 2022 11:54:24 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86k04hmkf3.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="58752"; posting-host="KiP7B6UDtf9WpJXNvjWpEg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
X-Notice: Filtered by postfilter v. 0.9.2
Cancel-Lock: sha1:cLorrS6X0JU6AZ+XOC4Q3zQQoxk=
 by: Julieta Shem - Sun, 30 Oct 2022 14:54 UTC

ram@zedat.fu-berlin.de (Stefan Ram) writes:

> Julieta Shem <jshem@yaxenu.org> writes:
>>My desire seems to imply that I need a union-like data structure.
>
> You only need to worry about such things in languages with
> static typing. For example, to have a function that can
> sometimes return an int value and at other times a string
> value in C, one would need a union.
>
> In Python with its dynamic typing, one does not need unions.
>
> def an_int_sometimes_and_sometimes_a_string( x ):
> if x:
> return 2
> else:
> return "two"

Nice. This means that I can solve my stack-union problem by writing a
procedure --- say stack(...) --- that sometimes gives me Empty() and
sometimes gives me Stack().

>>> stack()
Empty()

>>> stack(1,2,3,4)
Stack(4, Stack(3, Stack(2, Stack(1, Empty()))))

The user interface of this non-empty case is that we're stacking up the
arguments, hence the number 1 ends up at the bottom of the stack.

def stack(*args):
if len(args) == 0:
return Empty()
else:
return Stack(args[-1], stack(*args[:-1]))

I realize now that I'm using the same solution of the /open()/
procedure. Depending on the arguments, open() produces a different type
of object.

> . If you should, however, be talking about the new "type hints":
> These are static and have "Union", for example, "Union[int, str]"
> or "int | str".

I ended up locating such features of the language in the documentation,
but I actually am not interested in declaring the type to the compiler
(or to the reader).

I was looking for a solution like yours --- thank you! ---, although I
was hoping for handling that situation in the construction of the Stack
object, which was probably why I did not find a way out. Right now I'm
looking into __new__() to see if it can somehow produce one type or
another type of object depending on how the user has invoked the class
object.

Terminology. By ``invoking the class object'' I mean expressions such
as Class1() or Class2(). ``Class1'' represents the object that
represents the class 1. Since the syntax is that of procedure
invokation, I say ``invoking the class object''.

Re: an oop question

<86leoxi5i7.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20102&group=comp.lang.python#20102

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!KiP7B6UDtf9WpJXNvjWpEg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Sun, 30 Oct 2022 14:30:08 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86leoxi5i7.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="48177"; posting-host="KiP7B6UDtf9WpJXNvjWpEg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
X-Notice: Filtered by postfilter v. 0.9.2
Cancel-Lock: sha1:pCK8ifbS9kP0cWsnCwFOMJ15GX0=
 by: Julieta Shem - Sun, 30 Oct 2022 17:30 UTC

Julieta Shem <jshem@yaxenu.org> writes:

[...]

>> . If you should, however, be talking about the new "type hints":
>> These are static and have "Union", for example, "Union[int, str]"
>> or "int | str".
>
> I ended up locating such features of the language in the documentation,
> but I actually am not interested in declaring the type to the compiler
> (or to the reader).
>
> I was looking for a solution like yours --- thank you! ---, although I
> was hoping for handling that situation in the construction of the Stack
> object, which was probably why I did not find a way out. Right now I'm
> looking into __new__() to see if it can somehow produce one type or
> another type of object depending on how the user has invoked the class
> object.
>
> Terminology. By ``invoking the class object'' I mean expressions such
> as Class1() or Class2(). ``Class1'' represents the object that
> represents the class 1. Since the syntax is that of procedure
> invokation, I say ``invoking the class object''.

An experiment. What's my definition of Stack? It's either Empty or
Pair, so it's a union. So let us create two inner classes (that is,
inner to Stack) and make them behave just like Empty and Pair. Using
__new__(), we can produce a Stack object that is sometimes Empty() and
sometimes Pair(...).

class Stack:
class StackEmpty(Empty):
pass
class StackPair(Pair):
pass
def __new__(clss, *args):
if len(args) == 0:
return Stack.StackEmpty()
else:
return Stack.StackPair(*args)

This does it. However, we are exposing the different types to the user.

>>> Stack()
Empty()

>>> Stack(1, Stack())
Pair(1, Empty())

Since we have our own copies of Empty and Pair inside Stack, we change
their representation.

class Stack:
class StackEmpty(Empty):
def __str__(self):
return "Stack()"
def __repr__(self):
return str(self)
class StackPair(Pair):
def __str__(self):
return "Stack({!r}, {})".format(self.first, str(self.rest))
def __repr__(self):
return str(self)
[...]

>>> Stack()
Stack()

>>> Stack(1, Stack())
Stack(1, Stack())

That's it. That's what I was looking for. However, I don't really like
the OOP approach here because of what's going to happen next.

Now we are free to move on with implementing push and pop, say. But
since Stack is really a union, we need to define push and pop on each of
these inner types that make up Stack. Let's do it and see what we get.

class StackEmpty(Empty):
[...]
def pop(self):
raise ValueError("cannot pop from an empty stack")
def push(self, x):
return Stack(x, self)

class StackPair(Pair):
def pop(self):
return self.first
def push(self, x):
return Stack(x, self)

The job is done.

>>> Stack().push("it")
Stack('it', Stack())

>>> Stack(1, Stack()).push(2).push(3)
Stack(3, Stack(2, Stack(1, Stack())))

We may observe that we had to write the same exact procedure /push/ in
both types. Sounds funny to say that it seems that we are too modular
here. I'm pretty sure you'll find a way to grab the procedure of one
class and apply it on the other, so I really think there's a way out of
not wasting keyboard-typing work and keeping things with a ``single
point of control''.

(*) Complete code

class Stack:
class StackEmpty(Empty):
def __str__(self):
return "Stack()"
def __repr__(self):
return str(self)
def pop(self):
raise ValueError("cannot pop from an empty stack")
def push(self, x):
return Stack(x, self)
class StackPair(Pair):
def __str__(self):
return "Stack({!r}, {})".format(self.first, str(self.rest))
def __repr__(self):
return str(self)
def pop(self):
return self.first
def push(self, x):
return Stack(x, self)
def __new__(clss, *args):
if len(args) == 0:
return Stack.StackEmpty()
else:
return Stack.StackPair(*args)

Re: an oop question

<js83p8FmhjtU1@mid.individual.net>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20106&group=comp.lang.python#20106

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From: past...@units.it (Giorgio Pastore)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Sun, 30 Oct 2022 21:06:00 +0100
Lines: 33
Message-ID: <js83p8FmhjtU1@mid.individual.net>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: individual.net 8jdSaPa/+rIQ+Hyp5KDG3g/qK0C7fUtM/nJpPZy6gUs+qoRPt8
Cancel-Lock: sha1:V1Rn27Zx/LvlKa+YgUA/LFx6r/E=
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0)
Gecko/20100101 Thunderbird/102.4.1
Content-Language: it
In-Reply-To: <86k04hmkf3.fsf@yaxenu.org>
 by: Giorgio Pastore - Sun, 30 Oct 2022 20:06 UTC

Il 30/10/22 15:54, Julieta Shem ha scritto:
> ram@zedat.fu-berlin.de (Stefan Ram) writes:
>
>> Julieta Shem <jshem@yaxenu.org> writes:
>>> My desire seems to imply that I need a union-like data structure.
>>
>> You only need to worry about such things in languages with
>> static typing. For example, to have a function that can
>> sometimes return an int value and at other times a string
>> value in C, one would need a union.
>>
>> In Python with its dynamic typing, one does not need unions.
>>
>> def an_int_sometimes_and_sometimes_a_string( x ):
>> if x:
>> return 2
>> else:
>> return "two"
>
> Nice. This means that I can solve my stack-union problem by writing a
> procedure --- say stack(...) --- that sometimes gives me Empty() and
> sometimes gives me Stack().
>
I think that Stefan Ram's suggestion provides a solution to the problem
of the stack, but not in a real OOP flavor.

You may find useful to learn about the possibilities of using Python
tools to implement a stack data structure and its manipulation methods.
A good introduction is at
https://realpython.com/how-to-implement-python-stack/

Giorgio

Re: an oop question

<stack-20221030212024@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20107&group=comp.lang.python#20107

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 30 Oct 2022 20:22:28 GMT
Organization: Stefan Ram
Lines: 28
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <stack-20221030212024@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org> <js83p8FmhjtU1@mid.individual.net>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de 9kwF/CB9rSOwfwQ2VHrhHgo71J/GMGl+ciT7mwxjiPSrvH
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Sun, 30 Oct 2022 20:22 UTC

Giorgio Pastore <pastgio@units.it> writes:
>You may find useful to learn about the possibilities of using Python
>tools to implement a stack data structure and its manipulation methods.
>A good introduction is at
>https://realpython.com/how-to-implement-python-stack/

I can't see how lists are not stacks.

|>>> s=[]
|>>> s.append(1)
|>>> s.append(2)
|>>> s.pop()
|2
|>>> s.pop()
|1
|>>> s.pop()
|Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
|IndexError: pop from empty list

So, for practical purposes, there is no need to implement a
stack class as far as I can understand it.

Maybe the OP wanted to implement a stack in a special way,
so that this stack is immutable and its implementation is
based on something like dotted pairs.

Re: an oop question

<mailman.840.1667169075.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20112&group=comp.lang.python#20112

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ros...@gmail.com (Chris Angelico)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Mon, 31 Oct 2022 09:31:01 +1100
Lines: 49
Message-ID: <mailman.840.1667169075.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
X-Trace: news.uni-berlin.de y6v6lGg5e3/nxQglYPvKdAtxwH5DNsoLBv8zj8a5lvJQ==
Return-Path: <rosuav@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=bETL2HAs;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.022
X-Spam-Evidence: '*H*': 0.96; '*S*': 0.00; '2022': 0.05; 'compiler':
0.09; 'ended': 0.09; 'represents': 0.09; 'writes:': 0.09;
'syntax': 0.15; 'chrisa': 0.16; 'experiment.': 0.16;
'expressions': 0.16; 'from:addr:rosuav': 0.16; 'from:name:chris
angelico': 0.16; 'instance': 0.16; 'object,': 0.16; 'procedure':
0.16; 'received:209.85.218': 0.16; 'should,': 0.16; 'static':
0.16; 'subject:oop': 0.16; 'wrote:': 0.16; 'subject:question':
0.17; 'probably': 0.17; 'to:addr:python-list': 0.20; 'language':
0.21; "what's": 0.22; 'code': 0.23; 'classes': 0.26; 'object':
0.26; 'example,': 0.28; 'concept': 0.32; 'empty': 0.32; 'here,':
0.32; 'message-id:@mail.gmail.com': 0.32; 'but': 0.32; "i'm":
0.33; 'mean': 0.34; 'header:In-Reply-To:1': 0.34;
'received:google.com': 0.34; 'handling': 0.35;
'from:addr:gmail.com': 0.35; 'mon,': 0.36; 'possibly': 0.36;
'using': 0.37; "it's": 0.37; 'received:209.85': 0.37; 'class':
0.37; 'way': 0.38; 'put': 0.38; 'received:209': 0.39; 'two': 0.39;
'methods': 0.39; 'still': 0.40; 'situation': 0.40; 'skip:o 10':
0.61; 'here': 0.62; 'everything': 0.63; 'definition': 0.64;
'produce': 0.65; 'yours': 0.65; 'let': 0.66; 'types': 0.67;
'right': 0.68; 'interested': 0.68; 'depending': 0.70; 'features':
0.75; 'out.': 0.80; 'construction': 0.81; '(that': 0.84; 'stack,':
0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
h=to:subject:message-id:date:from:in-reply-to:references:mime-version
:from:to:cc:subject:date:message-id:reply-to;
bh=3brYqdESfI4QKa521sV+6UP4TBBrpQAWkpkp+/03iJI=;
b=bETL2HAsayfPVlllQ5V/1Ve52HgQ9L9OE/NvW4gKnuOE46eEsbgt1ggmuqFPox9fuo
lOM9N0nSz+3z+IgZU08mRtYwR759HZGDgkOAtQSOdrw46i/6gfAyItWPzqpsDtMdHeyh
3FaU/x5ZAyWf27VOhECwoNvh+Nj6tSkmFz1asfDtz9XSjJ7o4DKSZFpz/eabZEUFgkEF
KXdk0lOB1hDvzC5Yze7fNz4BOUT4kUFhX6b/8TXP8MmJEQ+Y7YZEITl6ODj7TSXev1H4
s36SBcffE3G2nSzqvZTY9b9Nl3SOxr2XhJfYuLCeByAazQRpJ08nEjhCQtjK/H09HFFi
gw0g==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20210112;
h=to:subject:message-id:date:from:in-reply-to:references:mime-version
:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to;
bh=3brYqdESfI4QKa521sV+6UP4TBBrpQAWkpkp+/03iJI=;
b=eAKeS9WEs0vwb9+izdBFH/sJz1rNQ/GAkrkwn3YYiP+NJhmhASR9WXArirtIgVbXki
6/Ypckh+vW3SbT/IQ5NvBBdXLhN/qkEDSNwin1O4m72hefC6RhFq5CbqYctUd9+ksIGf
rCwSQ8JX0s6gqqBWgcxIvYYdDu/3egyttcD2VxBNDP0Hhf3wO5Y8D/KLeZof//vFGSOt
yC31SXohlcNu+sfUpoC8XFvJzzfQPGW4RT9QJIuUNZ8RinHvgZpD51DnFTzEWv8mJ+wu
2YtCdpGQBDccWxW8ZfT1pBVbJ4OQRZS9UuCEWZIAD2CYRye0z72EgGdWU0c+EnhVsiuq
BjRw==
X-Gm-Message-State: ACrzQf2wD3V0sW7z8laBhksxGcilsl6FQSNidJVRxJ+oyuJ7TyWvdz7x
gBwZMnqHXUBAN+AriRH5KRXz8gd5hy8Vr1r6jlSlDR7b
X-Google-Smtp-Source: AMsMyM4iKKS5nacK114b8AViDuydCmo5/Mszfw07lGhek+VDRRDFOqBOzVcHPlfrdahXTopg/+Ppwk2UhTaEtXOisQM=
X-Received: by 2002:a17:907:6da3:b0:78e:2a5f:5aaf with SMTP id
sb35-20020a1709076da300b0078e2a5f5aafmr10004760ejc.554.1667169073113; Sun, 30
Oct 2022 15:31:13 -0700 (PDT)
In-Reply-To: <86leoxi5i7.fsf@yaxenu.org>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
 by: Chris Angelico - Sun, 30 Oct 2022 22:31 UTC

On Mon, 31 Oct 2022 at 09:05, Julieta Shem <jshem@yaxenu.org> wrote:
>
> Julieta Shem <jshem@yaxenu.org> writes:
>
> [...]
>
> >> . If you should, however, be talking about the new "type hints":
> >> These are static and have "Union", for example, "Union[int, str]"
> >> or "int | str".
> >
> > I ended up locating such features of the language in the documentation,
> > but I actually am not interested in declaring the type to the compiler
> > (or to the reader).
> >
> > I was looking for a solution like yours --- thank you! ---, although I
> > was hoping for handling that situation in the construction of the Stack
> > object, which was probably why I did not find a way out. Right now I'm
> > looking into __new__() to see if it can somehow produce one type or
> > another type of object depending on how the user has invoked the class
> > object.
> >
> > Terminology. By ``invoking the class object'' I mean expressions such
> > as Class1() or Class2(). ``Class1'' represents the object that
> > represents the class 1. Since the syntax is that of procedure
> > invokation, I say ``invoking the class object''.
>
> An experiment. What's my definition of Stack? It's either Empty or
> Pair, so it's a union. So let us create two inner classes (that is,
> inner to Stack) and make them behave just like Empty and Pair. Using
> __new__(), we can produce a Stack object that is sometimes Empty() and
> sometimes Pair(...).
>

The most straight-forward way to represent this concept in an
object-oriented way is subclassing.

class Stack:
... # put whatever code is common here

class Empty(Stack):
... # put Empty-specific code here, possibly overriding Stack methods

class Pair(Stack):
... # ditto, overriding or augmenting as needed

This way, everything is an instance of Stack, but they are still
distinct types for when you need to distinguish.

ChrisA

Re: an oop question

<mailman.843.1667174708.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20115&group=comp.lang.python#20115

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: gweathe...@uchc.edu (Weatherby,Gerard)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Mon, 31 Oct 2022 00:03:27 +0000
Lines: 155
Message-ID: <mailman.843.1667174708.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<SA1PR14MB585584E0C9313370167F2C2BB9379@SA1PR14MB5855.namprd14.prod.outlook.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de fQzpgzurtuNt7DtE4MdlvgYvCRxTmK+6qAk+gHGS9wZw==
Return-Path: <prvs=0303024f1a=gweatherby@uchc.edu>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=uchc.edu header.i=@uchc.edu header.b=J8wDfcTi;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.001
X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'def': 0.04; 'traceback':
0.04; '(most': 0.05; '2022': 0.05; 'last):': 0.05; '&gt;&gt;&gt;':
0.07; 'class.': 0.07; 'string': 0.07; 'that?': 0.07; 'difficulty':
0.09; 'else:': 0.09; 'knowledge.': 0.09; 'reasoning': 0.09;
'received:namprd14.prod.outlook.com': 0.09; 'represents': 0.09;
'studying': 0.09; 'typeerror:': 0.09; 'url-ip:13.107.213.67/32':
0.09; 'url-ip:13.107.213/24': 0.09; 'url-ip:13.107.246.67/32':
0.09; 'url-ip:13.107.246/24': 0.09; 'url:mailman': 0.15; '(*)':
0.16; '***': 0.16; 'arguments:': 0.16; 'attributes': 0.16;
'derive': 0.16; 'desire': 0.16; 'generally,': 0.16; 'oop': 0.16;
'oop.': 0.16; 'question,': 0.16; 'reuse': 0.16; 'skip:{ 30': 0.16;
'stack.': 0.16; 'structure.': 0.16; 'subject:oop': 0.16;
'url:urldefense': 0.16; 'url:v3': 0.16; 'october': 0.17;
'subject:question': 0.17; "can't": 0.17; 'to:addr:python-list':
0.20; 'first,': 0.22; 'organize': 0.22; 'purposes': 0.22; 'skip:_
10': 0.22; 'code': 0.23; 'skip:p 30': 0.23; 'idea': 0.24; 'to:name
:python-list@python.org': 0.24; 'section': 0.25; 'url:listinfo':
0.25; 'seems': 0.26; 'tried': 0.26; 'classes': 0.26;
'header:Received:9': 0.26; 'interface': 0.26; 'opening': 0.26;
'received:edu': 0.26; '>>>': 0.28; 'email addr:python.org&gt;':
0.28; 'example,': 0.28; 'whole': 0.30; 'comment': 0.31; 'raise':
0.31; 'think': 0.32; 'question': 0.32; '"",': 0.32; 'carefully':
0.32; 'context': 0.32; 'do.': 0.32; 'empty': 0.32; 'good.': 0.32;
'here,': 0.32; 'python-list': 0.32; 'but': 0.32; "i'm": 0.33;
'there': 0.33; 'particular': 0.33; 'same': 0.34; 'header:In-Reply-
To:1': 0.34; "we're": 0.35; 'missing': 0.37; 'received:filterd':
0.37; 'received:pps.filterd': 0.37; 'class': 0.37; 'this.': 0.37;
'url-ip:13.107/16': 0.38; 'file': 0.38; 'way': 0.38; 'enough':
0.39; 'otherwise': 0.39; 'date:': 0.39; 'list': 0.39; 'use': 0.39;
'methods': 0.39; 'on.': 0.39; 'rest': 0.39; 'wrote': 0.39; 'base':
0.40; 'done.': 0.40; 'both': 0.40; 'want': 0.40; 'should': 0.40;
'charset:windows-1252': 0.60; 'email.': 0.61; 'introduction':
0.61; 'skip:h 10': 0.61; 'from:': 0.62; 'me.': 0.62; 'to:': 0.62;
'here': 0.62; 'public': 0.63; 'pass': 0.64; "you'd": 0.64;
'definition': 0.64; 'your': 0.64; 'produce': 0.65; 'look': 0.65;
'required': 0.65; 'wish': 0.66; 'let': 0.66; 'back': 0.67;
'right': 0.68; 'sequence': 0.69; 'url-ip:52.6/16': 0.69; 'url-
ip:lookup error': 0.70; 'them,': 0.70; "you'll": 0.73; 'manage':
0.73; 'bear': 0.76; 'clicking': 0.76; 'produces': 0.76; 'links.':
0.81; 'attention:': 0.84; 'email name:&lt;python-list': 0.84;
'good,': 0.84; 'represented': 0.84; 'self)': 0.84; 'skip:& 50':
0.84; 'pop': 0.91; 'union': 0.91
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=uchc.edu;
h=from : to : subject :
date : message-id : references : in-reply-to : content-type :
mime-version; s=UCHC03162020;
bh=D1Ssp2zv1xs8mMy5HXI3z6/8pSXbhNJnv+l3vV+aU9U=;
b=J8wDfcTi9X9oT6GP6BSpjDiRrn3UzujETXNbA7P/uoCl37YXX7IkID25v9xG3TlulWPy
d5AU7Epn6N+tnBefmv35BgE7ffIsH+BnOHvGQPcJ7LKPc/s6Co2tZA1jYSgKPoA2NUQw
24U0W39H5YD3UfTkQ4Qr8IGPlh4tjpAB5L7pFae57wXgaik2X5lVeexqWKq6Wgs1j7/M
2VREpesk5TDOMSpMlUjiBd5RYVRhJhW1Ax9HTnXbPpJ8qE3wAHy1Hn/G4Axrfdggllh1
M8qEoSsk1gteZi/KqXLo7GwdpnFkyBu4DiF7dMLrE8udUtDr8pDyaETZPRr8yVUZH5mE Xg==
ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none;
b=OXbfRThcFd18yM+Mv072JLTJxu8seX607ZujZwiHax8NMN9JiZOxui/lhtSzWGoiPCYO96IXKqlw0GXw2v61c5CxqMdcIqhWpZaUnMxw09Idz+/ACz1QuPrrhaBxD7Am+le5Ca2wChkb9DaLugOOst34bCo2/Eb3/SvsrZdm7n0DmwqiPwOK0VpAphBTOurrxCPQKa3uG8k8lccR5wiyfondm36mD+ATQnU8YK6S0y+ADMcaZDrOO2yqpB5463yzoTsOUvvbyHURKjyKf3QLOwh8tj2GVrPyakYbSKbgB0Jkvjv0Utg13qPHKUjme28USJwCfBoH7uAo1nNC8bmIYg==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com;
s=arcselector9901;
h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1;
bh=D1Ssp2zv1xs8mMy5HXI3z6/8pSXbhNJnv+l3vV+aU9U=;
b=dKPfNyiISpKH9gT+QoKwOOtu0pJUZxdIeHmqgJ2Pq867DoI1IAGNTLzCjYXWo0Gs3fZ5NT7J/I6zPUGCTF0VBAfLYfJnq1X9aTc85WvhYKU0wJZRH+/pkFVMw/j+4W+Grbt3+N1T2gTDFHuNfqNMSL4QKx2pl4snctcbBLCBXLTFaXOadYOj4AewuidqEF5ykIom6s0uKWdsfKh8Ruj3Hpzm+3Q42fpPXjX+S2Pe3lJbLUSajq09ZIUsNE+cuO0aTYZcTaWu+snfXwgb6Pw6UdD1z2xb5GG6BbecmzDVYAQG1kYU+C6Ahk+fPY7FktIiZGaLJG1RnDjIqtYsFfVepg==
ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass
smtp.mailfrom=uchc.edu; dmarc=pass action=none header.from=uchc.edu;
dkim=pass header.d=uchc.edu; arc=none
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=uchc.onmicrosoft.com;
s=selector2-uchc-onmicrosoft-com;
h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck;
bh=D1Ssp2zv1xs8mMy5HXI3z6/8pSXbhNJnv+l3vV+aU9U=;
b=kzsEr5YQFGDo0tcwxemOXK07kwjghk9sv8SO/5O8YC8rYs373xoTOFuLYar6RF+dsXji4melIxddJ+2D6Ypd7rNymf0VIYFjM2Y3AZhZH8HsddwcU4jTGh/ioWpp794d6b7yro+LJzlkeHFYtBV3kmeKlN+dk3DQo1IhnzoIrRE=
Thread-Topic: an oop question
Thread-Index: AQHY7KnGaizHbm0Alk2I9CmURQ24m64nniho
In-Reply-To: <86y1sxmmvo.fsf@yaxenu.org>
Accept-Language: en-US
Content-Language: en-US
X-MS-Has-Attach:
X-MS-TNEF-Correlator:
x-ms-publictraffictype: Email
x-ms-traffictypediagnostic: SA1PR14MB5855:EE_|BY5PR14MB3527:EE_
x-ms-office365-filtering-correlation-id: 3202aec0-360f-4add-28c4-08dabad35639
x-ms-exchange-senderadcheck: 1
x-ms-exchange-antispam-relay: 0
x-microsoft-antispam: BCL:0;
x-microsoft-antispam-message-info: Ugy/iaEOr0rNQrBcng1Ogk5kI+FYJcTQhqCIpIOTB5CfE5geaJewjpzJ3YDW7DhFUfDIg4Mjmrg5j9mRjDM9+97/bVuUHsKUJlXqyCeYlkcACXZqH03XTr/Da7/4TzWcSXOrshzWwdTXENI1eCWkSt9gWxZdVPQZga9YY62fw1/UZGi2iLI7Y0BmA6VG+3ZBBvpLFQo6mBoAS1q6HqbgNBnFRe8LJoEu7s3Ga53BEU0u2sGOzL3oRqaxGeNEVbpXxEc/WVhPRr9q8u+hFKwjvPlUUJCwxtEStQSng0XbzVdJw/cTJsmgYK6rdP4vVKV/pESPXLvdBLmSsh/fUCpjMC3Bxc9RRNW271WNYme3iMze5jTwQ+eAN+zm9kYhGq5Q6qE3J6+nUNQQfbSmMJjBMvyRi7N3aN8ITwb7/qZGcCs9R6VbqMual/yUcATgpEvfSREGEomRGzvNjLt0bEKpCoTaanTJtPI44wwJP7Lhb0fCR5t75TAh+VkSPUk8OsqYpf/OnFnBf/9XYYLVkB9d2Y4vQZ+OosNxkigGbbQ5ZrZhomNY28plfE5nlIgNm+Xtkm3Kt4DAzgP1AZPmSPbKVNMY2wUi0WAwX/ZKwyiSYUOQA9yXL9YiB9k/iyWuLzTasDNtRSlu+nOszXQFSmEn2I8T2IYAIU/TnHW9LvQM5GC2sg19QTzDiadKWXp6c8GCbIO7fc/29yJ4gCScGAfH1/+tt7ginNz+5+W0BgeLS4m9yCzS/TNKn9tecHeSU8shiU01LVX9XkgLlR7ZgCwgj0evChIz2/6xrSLvQSk46FE=
x-forefront-antispam-report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:;
IPV:NLI; SFV:NSPM; H:SA1PR14MB5855.namprd14.prod.outlook.com; PTR:; CAT:NONE;
SFS:(13230022)(376002)(396003)(366004)(39840400004)(136003)(346002)(451199015)(53546011)(26005)(7696005)(6506007)(186003)(9686003)(71200400001)(2906002)(478600001)(966005)(166002)(41320700001)(38070700005)(122000001)(38100700002)(75432002)(86362001)(55016003)(83380400001)(786003)(33656002)(3480700007)(316002)(8936002)(76116006)(52536014)(64756008)(66556008)(66946007)(66446008)(66476007)(8676002)(110136005)(41300700001)(7116003)(5660300002)(91956017);
DIR:OUT; SFP:1101;
x-ms-exchange-antispam-messagedata-chunkcount: 1
x-ms-exchange-antispam-messagedata-0: T1hialCxrSQwoIimBNSH5Y24k/KabcPaP+89S06NACRgyNchAtxr/NW8
dRQ0qKRDHwjXQIB6MoRqsP8AUlTEvrtnXebfl8hijXv5owedZYtEy8ad
zo8Cy4AaeXlnn4GkNkQF8MiwiWyaln1JLOkQn7W0CfEfAxCZjaLQ9800
Pi3hUKFJ2icPYU3u83tMv5eqMZ1bQuwscau2ZyOZo9Ky1S2tiJuC28pN
8qt+fFnlOhuaaFEkSNXYfnGDHmF4XH5pv+GtMoxNRAN5tjgdYxsE2SxS
8OOwOjnw1hoCDQIilFMu+rjsqZ4QqFii3LzBW5nuzWl+npH1yVKWXN+W
I9J4y9to+CZpdbqF6pIhrTjzJpoDl4lfJQXdfyYGnP4W1hNk0flRwl88
n1Xj+39TYdeQ0kTtJXEQkf8Xn8Wm6Tc0G8jBVUvfZjj1mRsonUQHC034
YAnc5YbaHHOtCiBmlfEokgPfADjgspsi62iUTReb6PVtFqU/xrFV4Asw
W6ZgLmx7VWpNE9qUIqwbFOjIyXELoJnJ1SaqF6SARwwkKiiamDSjT4T5
dspkqVELnGl4OtL8QCsIPbrVMm/49pwiDLZzXsezvFuAxO0RzV310LaA
+IlOfQIn6YtifvzosncmLsIJ9jGFOcHpe/dyPctXfVVHP/Ql1EmgFSKP
J4nqVhPskIQEQrogWFy8yFeFUfAe+AyC4bF0Qpumn9jfgpPLr/BOEGBa
LysWyuUq8unKDbN+8NK5ok+aaj4ED9PzY0j1KOXQ1rbMIft416ThWQdp
V5rZSR0CA0o1UcROmZN8QQzAeBiT74KHQT4teJt0/TFL5yueoEUmT6KK
pALrwLg5TZzlwh3KYi88Eve9f6n8sh+Bn+QDOBpjYeodcm4VlWAFA7Ax
94zMAJMtD8qhwdQFQAQ0DLRUd95D7L7wGJn2GAotcetc5qIfe1rS/FnA
sHd250TcJdxC7tkO3kUyF54ntnv9wzV4fPP1oYUqavg6X82sD8sBi0Z8
86/iQ5HbwAF+qAqYIoRe0PR0YdxQGoNe1sA8fjnOjqLTe8MFNFtdoXGh
whbt4JHVrtMOwdgfZIdFOy0LbMJphOy5NlWdh+Wml1pQZpZBKNLbpiuF
10rAi2xXwfXLoILX8jMfvBhPvbSgoLEMB/VyUPYBY8wFKcPm3FExPLc4
NDQiNtj6mKGMi0f1/SdQiLNvBlEuGmjt0jWc9nv/h1GYzIMaiWseDH1A
Q8T/VekCCs/Zee7ostEpt9CHMhiH/zdgyjex5ctP+mzBPSPx50+nyQS8
UADp0lGPxtjlqHPUSJDorYqmt6d1i0UsWBFdrRS8e1HoOtjLZ2jETGAZ
CyNgXAHTiFkFljf06dlsNCYOIBliWgn/S/cTRwywTLg8Bf5Rn68KYuf/
54yPqJmY/3nGGO7SdPVFhUTcNsw2OdwXmez2wQ3O4UPnMRcfa9J2mhvK
MkK7RfR2kNf8hTxW9btKbhnrZuE8LHBnYdngsVW34ZiY64VAvYqYW9su
0XqEJ4FU/JY1t2klqUb3MX24GRL4aD2Krcs3YjAuTM0hgfi6npXkeAUW
ldoiMU4PLWt+e6dckOfIph0IFk1lCs1buDB7Ux2PT4Z9y8wAPooRQA
==
X-MS-Exchange-CrossTenant-AuthAs: Internal
X-MS-Exchange-CrossTenant-AuthSource: SA1PR14MB5855.namprd14.prod.outlook.com
X-MS-Exchange-CrossTenant-Network-Message-Id: 3202aec0-360f-4add-28c4-08dabad35639
X-MS-Exchange-CrossTenant-originalarrivaltime: 31 Oct 2022 00:03:27.3486 (UTC)
X-MS-Exchange-CrossTenant-fromentityheader: Hosted
X-MS-Exchange-CrossTenant-id: 5c82d83a-818a-4c16-b540-ded2344a7ad3
X-MS-Exchange-CrossTenant-mailboxtype: HOSTED
X-MS-Exchange-CrossTenant-userprincipalname: Mu4ktQA6rPSWbf1rc/MTAe7GvRhWdIaIgurqElcWOKL7j1LT+AWbbNsnSRpN1rtIpRp5LnW8KlDBUfJEoyd5Cg==
X-MS-Exchange-Transport-CrossTenantHeadersStamped: BY5PR14MB3527
X-Proofpoint-GUID: -VaX7rRvNRz78RJEr5OtXPpTSo7N9rlo
X-Proofpoint-ORIG-GUID: -VaX7rRvNRz78RJEr5OtXPpTSo7N9rlo
X-Proofpoint-Virus-Version: vendor=baseguard
engine=ICAP:2.0.205,Aquarius:18.0.895,Hydra:6.0.545,FMLib:17.11.122.1
definitions=2022-10-30_16,2022-10-27_01,2022-06-22_01
X-Proofpoint-Spam-Details: rule=outbound_notspam policy=outbound score=0
malwarescore=0 suspectscore=0
bulkscore=0 mlxlogscore=999 impostorscore=0 lowpriorityscore=0
priorityscore=1501 mlxscore=0 phishscore=0 spamscore=0 adultscore=0
clxscore=1011 classifier=spam adjust=0 reason=mlx scancount=1
engine=8.12.0-2210170000 definitions=main-2210300163
X-Content-Filtered-By: Mailman/MimeDel 2.1.39
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <SA1PR14MB585584E0C9313370167F2C2BB9379@SA1PR14MB5855.namprd14.prod.outlook.com>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
 by: Weatherby,Gerard - Mon, 31 Oct 2022 00:03 UTC

I don’t understand your implementation enough to comment specifically. What’s the definition of Pair? (i.e. what methods and public attributes does it have?) (I manage to escape Lisp as an undergrad)

To answer your question generally, Union’s are not OO. If you want Pair and Stack to have the same interface create an abstract base class and derive both of them from it.

https://docs.python.org/3/library/abc.html

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Julieta Shem <jshem@yaxenu.org>
Date: Sunday, October 30, 2022 at 5:51 PM
To: python-list@python.org <python-list@python.org>
Subject: an oop question
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

I have a question about a particular case I'm working on. I'm studying
OOP. To ask the question, I'm going to have to introduce you my context
here, so you'll need to bear with me. If you'd like to see the question
right away, go to the section ``My difficulty in encapsulating a
union''.

(*) Introduction

I wrote the classes

class Empty:
...
class Pair:
...

With them, I can (sort of) make a union of them and build a Lisp-like
list by defining that my Lisp-like list is either Empty or a Pair. For
instance, here's a Lisp-like sequence that represents the string "abc".

>>> Pair.fromIterable("abc")
Pair('a', Pair('b', Pair('c', Empty())))

So far so good. (``Full'' code at the end of this message, if you'd
like to more carefully look into my reasoning there.)

(*) How to build a stack?

These Lisp-like sequences are clearly a stack. You pop an element from
it by grabbing the first element. You push an element on to it by just
pairing the new element with the current stack. For instance, let's pop
the 1-string "a" off of the stack.

>>> ls = Pair.fromIterable("abc")
>>> ls.first
'a'
>>> ls = ls.rest
>>> ls
Pair('b', Pair('c', Empty()))

Done. Let's push it back on.

>>> ls = Pair("a", ls)
>>> ls
Pair('a', Pair('b', Pair('c', Empty())))

So far so good, but when it comes to building a better user interface
for it I have no idea how to do it. I think one of the purposes of OOP
is to organize code hierarchically so that we can reuse what we wrote.
So I tried to make a Stack by inheriting Pair.

class Stack(Pair):
pass

>>> Stack(1, Empty())
Stack(1, Empty())

Then I wrote pop and push.

>>> Stack(1, Empty()).pop()
1

>>> Stack(1, Empty()).push(2)
Stack(2, Stack(1, Empty()))

So far so good. Now let me show you what I can't do.

(*) The difficulty of encapsulating a union

The Lisp-like sequences we're building here are union-like data
structures. A /sequence/ is either Empty() or Pair(..., /sequence/). I
have not found a way to represent this either-or datastructure with a
class. For example, there is no way right now to build an empty Stack
by invoking the Stack constructor.

>>> Stack()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Pair.__init__() missing 2 required positional arguments: 'first' and 'rest'

As I designed, an empty Stack is represented by Empty(), which is a
whole other object. Users will have to know this. I wish I did not
have to burden my users with such knowledge. For instance, I wish the
answer was "Stack()" to the question of -- ``how can I build an empty
stack?''

My desire seems to imply that I need a union-like data structure. If
Stack is invoked with no arguments, it should produce Empty(), otherwise
it produces Pair() as it does today.

How can I achieve that?

(*) Code

class Pair:
def __init__(self, first, rest):
if not isinstance(rest, Pair) and not isinstance(rest, Empty):
raise ValueError("rest must be Empty or Pair")
self.first = first
self.rest = rest
def fromIterable(it):
if len(it) == 0:
return Empty()
else:
return Pair(it[0], Pair.fromIterable(it[1:]))
def __str__(self):
return "{}({!r}, {})".format(self.__class__.__name__, self.first, str(self.rest))
def __repr__(self):
return str(self)
def __len__(self):
return 1 + self.rest.__len__()

class Empty:
def __len__(self):
return 0
def __str__(self):
return "Empty()"
def __repr__(self):
return self.__str__()
def __new__(clss):
if not hasattr(clss, "saved"):
clss.saved = super().__new__(clss)
return clss.saved

class Stack(Pair):
def pop(self):
return self.first
def push(self, x):
return Stack(x, self)
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iK-T12707FwUmb1Qqxlxawj0i9z1tR9aCPWPoHzh5veCzlaFBY9pKfFZwGqg3sDjUqLPC2IZgGw4QI3sRg$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!iK-T12707FwUmb1Qqxlxawj0i9z1tR9aCPWPoHzh5veCzlaFBY9pKfFZwGqg3sDjUqLPC2IZgGw4QI3sRg$>

Re: an oop question

<86v8o0hlno.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20116&group=comp.lang.python#20116

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!A7ZQH8wsZnYK+dnGqR5EmA.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Sun, 30 Oct 2022 21:38:51 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86v8o0hlno.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="36476"; posting-host="A7ZQH8wsZnYK+dnGqR5EmA.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
X-Notice: Filtered by postfilter v. 0.9.2
Cancel-Lock: sha1:2ME9DuafE+b/v0c3CK/iIIoOO/s=
 by: Julieta Shem - Mon, 31 Oct 2022 00:38 UTC

Chris Angelico <rosuav@gmail.com> writes:

> On Mon, 31 Oct 2022 at 09:05, Julieta Shem <jshem@yaxenu.org> wrote:
>>
>> Julieta Shem <jshem@yaxenu.org> writes:
>>
>> [...]
>>
>> >> . If you should, however, be talking about the new "type hints":
>> >> These are static and have "Union", for example, "Union[int, str]"
>> >> or "int | str".
>> >
>> > I ended up locating such features of the language in the documentation,
>> > but I actually am not interested in declaring the type to the compiler
>> > (or to the reader).
>> >
>> > I was looking for a solution like yours --- thank you! ---, although I
>> > was hoping for handling that situation in the construction of the Stack
>> > object, which was probably why I did not find a way out. Right now I'm
>> > looking into __new__() to see if it can somehow produce one type or
>> > another type of object depending on how the user has invoked the class
>> > object.
>> >
>> > Terminology. By ``invoking the class object'' I mean expressions such
>> > as Class1() or Class2(). ``Class1'' represents the object that
>> > represents the class 1. Since the syntax is that of procedure
>> > invokation, I say ``invoking the class object''.
>>
>> An experiment. What's my definition of Stack? It's either Empty or
>> Pair, so it's a union. So let us create two inner classes (that is,
>> inner to Stack) and make them behave just like Empty and Pair. Using
>> __new__(), we can produce a Stack object that is sometimes Empty() and
>> sometimes Pair(...).
>>
>
> The most straight-forward way to represent this concept in an
> object-oriented way is subclassing.
>
> class Stack:
> ... # put whatever code is common here
>
> class Empty(Stack):
> ... # put Empty-specific code here, possibly overriding Stack methods
>
> class Pair(Stack):
> ... # ditto, overriding or augmenting as needed
>
> This way, everything is an instance of Stack, but they are still
> distinct types for when you need to distinguish.

Can you provide a small example? I can't see what you mean, but it
seems interesting.

Re: an oop question

<mailman.845.1667177918.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20118&group=comp.lang.python#20118

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: PythonL...@DancesWithMice.info (dn)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Mon, 31 Oct 2022 13:58:28 +1300
Organization: DWM
Lines: 60
Message-ID: <mailman.845.1667177918.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
<js83p8FmhjtU1@mid.individual.net>
<stack-20221030212024@ram.dialup.fu-berlin.de>
<2bf88e5b-d0ea-e285-e22c-a7c78938c6e3@DancesWithMice.info>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de vOvCiKATeUmA7Puewp9K1w6JEh6aZkerUDplO/bIT0Wg==
Return-Path: <PythonList@DancesWithMice.info>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=danceswithmice.info header.i=@danceswithmice.info
header.b=Q2ZnZStp; dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.000
X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; '(which': 0.04; '(most':
0.05; 'is.': 0.05; 'last):': 0.05; 'class.': 0.07; 'intermediate':
0.07; 'ram': 0.07; '=dn': 0.09; 'from:addr:danceswithmice.info':
0.09; 'from:addr:pythonlist': 0.09; 'methods,': 0.09; 'writes:':
0.09; 'aggregate': 0.16; 'collection,': 0.16; 'confused.': 0.16;
'descriptive': 0.16; 'dotted': 0.16; 'helpful,': 0.16; 'humans':
0.16; 'message-id:@DancesWithMice.info': 0.16; 'received:51.254':
0.16; 'received:51.254.211': 0.16; 'received:51.254.211.219':
0.16; 'received:cloud': 0.16; 'received:rangi.cloud': 0.16;
'sadly,': 0.16; 'stack.': 0.16; 'stacks.': 0.16; 'subject:oop':
0.16; 'such,': 0.16; 'url-ip:172.67.43/24': 0.16; '|>>>': 0.16;
'wrote:': 0.16; 'python': 0.16; 'subject:question': 0.17;
'instead': 0.17; "can't": 0.17; 'implement': 0.19; 'to:addr
:python-list': 0.20; 'maybe': 0.22; 'code': 0.23; 'list,': 0.24;
'seems': 0.26; 'stefan': 0.26; 'header:User-Agent:1': 0.30;
'header:Organization:1': 0.31; '"",': 0.32; 'empty': 0.32;
'logical': 0.32; 'structure': 0.32; 'there': 0.33; 'header:In-
Reply-To:1': 0.34; 'lists': 0.37; "skip:' 10": 0.37; 'special':
0.37; 'using': 0.37; 'class': 0.37; 'received:192.168': 0.37;
'file': 0.38; 'read': 0.38; 'two': 0.39; 'least': 0.39; 'list':
0.39; 'methods': 0.39; 'learn': 0.40; 'something': 0.40;
'introduction': 0.61; 'method': 0.61; 'personal': 0.64;
'received:51': 0.64; 'mind.': 0.67; 'per': 0.68; 'operations':
0.68; 'cost': 0.69; 'terms': 0.70; 'too.': 0.70; 'tools': 0.74;
'practical': 0.84; 'coded': 0.84; 'inherit': 0.84; 'thus,': 0.84;
'pop': 0.91; 'agreed': 0.95
DKIM-Filter: OpenDKIM Filter v2.11.0 vps.rangi.cloud 704465631
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=danceswithmice.info;
s=staff; t=1667177917;
bh=BZXemd37GZOwNI2ujg4DW1A5ZlFBBvQDNwfV+tnodAc=;
h=Date:Subject:To:References:From:In-Reply-To:From;
b=Q2ZnZStpRTzR5UEbH+iWcjzjVtSrUTmiCuvQZzOcXOuWSoUDPbyIfeuDb1oclNziz
VKYYr55UdGC06oH3vh8Ot70DUM2BL98XShQel8snamQHD4efCi8MfR7Hb1mSUfc9pS
DehK3L9NkJ08yiNmJIod/R7mGEIJ4V5lxqiQIXegLjlluxpbeoU+vTFrsSLXmp2P+E
XiF7g5mpKS1jw81l7bALbM7b2tGMcjLbHeWhuCjVtmShb+xfosF5Sr5noGOvOPr+WP
xf5uNd+tQprvzC5YqoSfR2pojqI32N2iSbnn9Ngqe1ins6klPZUeG0qyQRp4nyVRFC
e1qPMiYGivEsA==
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101
Thunderbird/102.4.0
Content-Language: en-GB
In-Reply-To: <stack-20221030212024@ram.dialup.fu-berlin.de>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <2bf88e5b-d0ea-e285-e22c-a7c78938c6e3@DancesWithMice.info>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
<js83p8FmhjtU1@mid.individual.net>
<stack-20221030212024@ram.dialup.fu-berlin.de>
 by: dn - Mon, 31 Oct 2022 00:58 UTC

On 31/10/2022 09.22, Stefan Ram wrote:
> Giorgio Pastore <pastgio@units.it> writes:
>> You may find useful to learn about the possibilities of using Python
>> tools to implement a stack data structure and its manipulation methods.
>> A good introduction is at
>> https://realpython.com/how-to-implement-python-stack/
>
> I can't see how lists are not stacks.

Agreed - in terms of functionality(!)

> |>>> s=[]
> |>>> s.append(1)
> |>>> s.append(2)
> |>>> s.pop()
> |2
> |>>> s.pop()
> |1
> |>>> s.pop()
> |Traceback (most recent call last):
> | File "<stdin>", line 1, in <module>
> |IndexError: pop from empty list
>
> So, for practical purposes, there is no need to implement a
> stack class as far as I can understand it.
>
> Maybe the OP wanted to implement a stack in a special way,
> so that this stack is immutable and its implementation is
> based on something like dotted pairs.

Code is for humans to read too. Accordingly, instead of "s", preference
for "stack" - per OP terminology.

The OP has coded pop() and push() methods, which are familiar/taught as
'the' stack operations in every 'intro to algorithms' (or intermediate
'data-structures') class.

Sadly, whereas there is list.pop(), the equivalent "push" method is
append(). Thus, a (small) dissonance in one's mind.

Writing a Stack class is unnecessary - at least given list, it is.
However, having called the structure "stack" to be descriptive and
helpful, it seems logical to continue by referring to the methods as
"push" and "pop".
(which is why many of us have such 'utilities'/snippets sitting-ready in
a personal library)

The OP has already coded such, so no cost to keep.

(returning to the OP)
Like @Gerard, am confused. There are two types: Pair and Empty.
Thereafter the need is to keep them on a stack. The stack is a
collection, an aggregate of 'whatever'. Why inherit from/to Stack?
(is this a 'Lisp thing'?)

--
Regards,
=dn

Re: an oop question

<mailman.848.1667193727.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20122&group=comp.lang.python#20122

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ros...@gmail.com (Chris Angelico)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Mon, 31 Oct 2022 16:21:53 +1100
Lines: 66
Message-ID: <mailman.848.1667193727.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
X-Trace: news.uni-berlin.de NXVGweOsMrtfH9sW6aSkogWApXIvkc62VwWGy7n5Gn4w==
Return-Path: <rosuav@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=RVRmz5rP;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.006
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'def': 0.04; '2022': 0.05;
'class.': 0.07; 'angelico': 0.09; 'construct': 0.09; 'example:':
0.09; 'instances': 0.09; 'moved': 0.09; 'writes:': 0.09; 'chrisa':
0.16; 'classes,': 0.16; 'easiest': 0.16; 'from:addr:rosuav': 0.16;
'from:name:chris angelico': 0.16; 'instance': 0.16;
'interesting.': 0.16; 'iterate': 0.16; 'mean,': 0.16; 'setup,':
0.16; 'stack.': 0.16; 'subject:oop': 0.16; 'variant': 0.16;
'wrote:': 0.16; 'python': 0.16; 'subject:question': 0.17; "can't":
0.17; 'to:addr:python-list': 0.20; 'skip:_ 10': 0.22; 'code':
0.23; 'anything': 0.25; 'seems': 0.26; "isn't": 0.27; 'chris':
0.28; 'expect': 0.28; 'example,': 0.28; 'putting': 0.31; 'raise':
0.31; 'question': 0.32; 'concept': 0.32; 'empty': 0.32; 'here,':
0.32; 'message-id:@mail.gmail.com': 0.32; 'but': 0.32; 'there':
0.33; 'able': 0.34; 'header:In-Reply-To:1': 0.34;
'received:google.com': 0.34; 'from:addr:gmail.com': 0.35; 'mon,':
0.36; 'possibly': 0.36; 'really': 0.37; "it's": 0.37;
'received:209.85': 0.37; 'class': 0.37; 'way': 0.38; 'could':
0.38; 'put': 0.38; 'received:209': 0.39; 'received:209.85.208':
0.39; 'methods': 0.39; 'still': 0.40; 'both': 0.40; 'should':
0.40; 'provide': 0.60; 'skip:o 10': 0.61; 'skip:i 20': 0.62;
'here': 0.62; 'true': 0.63; 'everything': 0.63; 'your': 0.64;
'types': 0.67; 'more,': 0.67; 'that,': 0.67; 'items': 0.68;
"you'll": 0.73; '(that': 0.84; 'self)': 0.84; 'stack,': 0.84;
'sure.': 0.84; 'type,': 0.84; 'stays': 0.91
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
h=to:subject:message-id:date:from:in-reply-to:references:mime-version
:from:to:cc:subject:date:message-id:reply-to;
bh=Q72l6XcHCxHggiPRNGZfkvNbkiZjtUvNG/VAtkM+ZXE=;
b=RVRmz5rP4TTPqT2J9Cf7RV9TmQZYlPBgX5ofsAjN5TycjoEGMWdPm1/S3BsUP7u3QW
2oPbs3WdmX3xNiUjnvY0gaSksyHH4bMSZrX0G2zlAee60Dqbz6eWsxfKmv6347LVpxqS
YSwSQyHCiMTJwJdUWuZBonA0CHbAorvwKTnBySdN5vFv/+dqVUTMAH2xCGrzqPGt1/3R
f9ERPW2IxSy7YcE8WwApk/LBfQ1bLjcwG5ydH6RrseJMhEVHfCUe7X6yunUzZNuwOwYC
sLOdm6sNr4gvcG8tWDvA/0hhfZwYOUHoGPs0Tb1S8+qIcAHt/iJJxIqwKyyDw2hAEQQq
FuYQ==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20210112;
h=to:subject:message-id:date:from:in-reply-to:references:mime-version
:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to;
bh=Q72l6XcHCxHggiPRNGZfkvNbkiZjtUvNG/VAtkM+ZXE=;
b=iIs+kUrqKoK84qICpwpc5FFXmtMEgvel50E3VxBvaXi2NkDGK3TKD+CRplwkB7fbGw
HL56UPfqLNY6scuUjlTLWjofqmqgM49+gzACQtFpmFU7WqWQJO/AR5Hy104JzKRDuuIh
4PKYNCk7qfV9Zd1wNzm+WPD8EcAKNDMaDapbAWQG6S7w1PY3VGY7P+G0NOHNTpUjy7yR
3Bh+vl7KYD4D2NYGZ9tRnVORl2IfK3LY0oVY0SzQGIhiLOrZZ5p2ouguSd79+8qIAQgs
mULGyEgAZIqD3caxzdNtJlxt428A0O/DpYG87AR9Hu3D325Zwnf0+s4fvfuvqFulMOeb
ghqA==
X-Gm-Message-State: ACrzQf02irxctCQxSIo1MSd4bDpPyxm/9KQKXpqcJAi8WEK0XFkW0r1L
l65fAJBwAhpVu4l5mTSYiyJZDNrlzEZCZ1T65n8vEoR7
X-Google-Smtp-Source: AMsMyM5d/9psc3jnwAfnEUrYu4lU+S7bm694HNPAsJC54J8IAtKRuk57G83Qw/NJu7UTudNwBSCP23on98bLP4LO2hE=
X-Received: by 2002:aa7:c6cd:0:b0:461:87ab:3255 with SMTP id
b13-20020aa7c6cd000000b0046187ab3255mr11936480eds.193.1667193724637; Sun, 30
Oct 2022 22:22:04 -0700 (PDT)
In-Reply-To: <86v8o0hlno.fsf@yaxenu.org>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
 by: Chris Angelico - Mon, 31 Oct 2022 05:21 UTC

On Mon, 31 Oct 2022 at 14:38, Julieta Shem <jshem@yaxenu.org> wrote:
>
> Chris Angelico <rosuav@gmail.com> writes:
>
> > The most straight-forward way to represent this concept in an
> > object-oriented way is subclassing.
> >
> > class Stack:
> > ... # put whatever code is common here
> >
> > class Empty(Stack):
> > ... # put Empty-specific code here, possibly overriding Stack methods
> >
> > class Pair(Stack):
> > ... # ditto, overriding or augmenting as needed
> >
> > This way, everything is an instance of Stack, but they are still
> > distinct types for when you need to distinguish.
>
> Can you provide a small example? I can't see what you mean, but it
> seems interesting.

Sure. The easiest way would be to take your existing Empty and Pair
classes, have them subclass Stack, and don't bother putting any code
at all into Stack. Then construct an Empty and a few Pairs, and what
you'll see is that all of them are also instances of Stack.

After that, it's really a question of what you expect to be able to do
with either an Empty or a Pair. Anything that should be possible with
both types (that is, anything that should be possible with either
variant of Stack) should get moved into the Stack type, while anything
that is specific to one or the other stays in its own class. So here's
a very very simple example:

class Stack:
def prepend(self, other):
return Pair(other, self)

class Empty(Stack):
def is_last(self):
return True
def get_current(self):
raise ValueError("Stack empty")
def get_next(self):
raise ValueError("Stack empty")

class Pair(Stack):
def __init__(self, item1, item2):
self.item1 = item1
self.item2 = item2
def get_current(self):
return self.item1
def get_next(self):
return self.item2
def is_last(self):
return isinstance(self.item2, Empty)

With this setup, you can build a stack by prepending items onto an
Empty endpoint, and can iterate over it with the get_current and
get_next methods. (Making this actually iterable, so that it works
with a Python 'for' loop, would be a good exercise.)

In this example, there isn't much code in the Stack class. But you
could easily add more, and it would apply to both Empty and Pair.

ChrisA

Re: an oop question

<mailman.849.1667209022.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20123&group=comp.lang.python#20123

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: learn2pr...@gmail.com (Alan Gauld)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Mon, 31 Oct 2022 09:36:59 +0000
Lines: 121
Message-ID: <mailman.849.1667209022.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de K1TFWmDhKv0anwb+zjITTQ10r/VaOxCb0bc2z8gAfvqw==
Return-Path: <learn2program@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=QZQKc3M3;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.000
X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'def': 0.04; 'traceback':
0.04; '(most': 0.05; 'last):': 0.05; 'parameter': 0.05; 'class.':
0.07; 'thing.': 0.07; 'construct': 0.09; 'difficulty': 0.09;
'else:': 0.09; 'received:209.85.128.46': 0.09; 'received:mail-
wm1-f46.google.com': 0.09; 'typeerror:': 0.09; '(*)': 0.16;
'>>>>': 0.16; 'arguments:': 0.16; 'facilitate': 0.16; 'flickr':
0.16; 'from:name:alan gauld': 0.16; 'instance': 0.16; 'instead.':
0.16; 'message-id:@yahoo.co.uk': 0.16; 'oop': 0.16; 'oop.': 0.16;
'photo-blog': 0.16; 'reuse': 0.16; 'skip:{ 30': 0.16; 'stack.':
0.16; 'subject:oop': 0.16; 'them)': 0.16; 'url-
ip:79.170.44.132/32': 0.16; 'url-ip:79.170.44/24': 0.16; 'url-
ip:79.170/16': 0.16; 'url-ip:79/8': 0.16; 'url:alan-g': 0.16;
'url:alan_gauld': 0.16; 'url:alangauldphotos': 0.16; 'wrote:':
0.16; 'python': 0.16; 'subject:question': 0.17; "can't": 0.17;
'url:amazon': 0.19; 'to:addr:python-list': 0.20; 'doubt': 0.22;
'organize': 0.22; 'purposes': 0.22; 'skip:_ 10': 0.22; 'code':
0.23; 'idea': 0.24; 'to:name:python-list@python.org': 0.24;
'(and': 0.25; 'programming': 0.25; 'tried': 0.26; 'classes': 0.26;
'interface': 0.26; 'purpose': 0.28; 'example,': 0.28; 'header
:User-Agent:1': 0.30; 'approach': 0.31; 'default': 0.31; 'raise':
0.31; 'program': 0.31; 'think': 0.32; '"",': 0.32; 'do.': 0.32;
'empty': 0.32; 'good.': 0.32; 'received:192.168.1': 0.32; 'but':
0.32; "i'm": 0.33; 'there': 0.33; 'same': 0.34; 'mean': 0.34;
'header:In-Reply-To:1': 0.34; 'received:google.com': 0.34;
'trying': 0.35; 'usual': 0.35; 'from:addr:gmail.com': 0.35;
"we're": 0.35; 'missing': 0.37; 'really': 0.37; "it's": 0.37;
'received:209.85': 0.37; 'author': 0.37; 'class': 0.37; 'this.':
0.37; 'received:192.168': 0.37; 'file': 0.38; 'way': 0.38;
'could': 0.38; 'put': 0.38; 'received:209': 0.39; 'use': 0.39;
'rest': 0.39; 'wrote': 0.39; 'alan': 0.40; 'true.': 0.40; 'learn':
0.40; 'method': 0.61; 'skip:h 10': 0.61; 'above': 0.62; 'here':
0.62; 'follow': 0.62; 'pass': 0.64; 'your': 0.64; 'required':
0.65; 'let': 0.66; 'outside': 0.67; 'right': 0.68; 'url:author':
0.69; 'site': 0.70; 'too.': 0.70; 'leads': 0.81; 'biggest': 0.84;
'delegation': 0.84; 'good,': 0.84; 'implies': 0.84; 'inheritance':
0.84; 'inputs': 0.84; 'self)': 0.84; 'mistakes': 0.91; 'pop':
0.91; 'union': 0.91
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112;
h=content-transfer-encoding:in-reply-to:references:to:subject
:user-agent:mime-version:date:message-id:from:from:to:cc:subject
:date:message-id:reply-to;
bh=jaopNGsJ03LwxhWMM59LpyhuuZ4CRU9WiC23bLyNI2M=;
b=QZQKc3M3vlAKPErPhvM08atSmA0E1KJlknmv+T7nPtrEvZ5PLPVoeuVGIsH9/YGoxv
HCbJXBlaibq9dPkrNM9GBaIJjBbTF9zJSvAuZ0x6Pzaeg/KJuHJyf+U95LoMLTdGxfBP
ZMy/tOvCz7Tq3Bqn+3lE5guLM81tAs+JE0hKEXYlGLhdbvvYxym4rhAG34BCWD8WKh96
1T/jFS6qxe2c2771AzGKS8YZabC4g26gSymy1a8HmSlTRcVnmUVxls11oTj60mPwYMKa
MSUGS22CrSKSmsZo/La3Nf9ETKFBvKFRb3PLWSNR5LCDgyeI7GPCgUEx5eZOZnq0neme
N3SA==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20210112;
h=content-transfer-encoding:in-reply-to:references:to:subject
:user-agent:mime-version:date:message-id:from:x-gm-message-state
:from:to:cc:subject:date:message-id:reply-to;
bh=jaopNGsJ03LwxhWMM59LpyhuuZ4CRU9WiC23bLyNI2M=;
b=DxeYGtuRX7Z+2KSTRk6iSssGuIaHdNwS4+yVQBFVOq4ULgl1vjaIyRw7LH649540Wl
yfaetFH9271Acqg61D5JhxO1uzw8/dRIEA/ACTD1hRH3b3plSF7RPMtDwP5o5Jr6nAnT
Nv4/u5dkeIR+GdwGWcY9RgtTevMh0lMXnJzidZOH4sCXWgBMwAyxaH6FhFhKNIyqHBXL
A2T10K/Ym4zcIvT0fiAgR7A85wDfAnSFEfub31uQulADD/Lisx+wLhEheE/HRQzHUou+
+93i4cw/7aJ5oVsfDe1jMamAUWSw3WRf/NWclk2jwUeTyH8FqzroM5Fcs9dBQm9X3CxR
/Sbw==
X-Gm-Message-State: ACrzQf21LB8jgqjEQSMlQ5MSaqNi8FrkP3zsTWnzY37BHqeHxfFhHT2F
egjGxAPnhWGrF9ArDD6cE0aQG/Y1YYDa9g==
X-Google-Smtp-Source: AMsMyM5upcY25fkP4M+tz7xkoIfvwpPGd8JYeasSTuGGfbn6TX8pSt0CDtVL7iahFgYCHJZ0yCRgfg==
X-Received: by 2002:a05:600c:1f11:b0:3cf:73f0:b753 with SMTP id
bd17-20020a05600c1f1100b003cf73f0b753mr1385686wmb.100.1667209021100;
Mon, 31 Oct 2022 02:37:01 -0700 (PDT)
X-Google-Original-From: Alan Gauld <alan.gauld@yahoo.co.uk>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0)
Gecko/20100101 Thunderbird/102.4.0
In-Reply-To: <86y1sxmmvo.fsf@yaxenu.org>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
 by: Alan Gauld - Mon, 31 Oct 2022 09:36 UTC

On 30/10/2022 14:01, Julieta Shem wrote:

> I wrote the classes
>
> class Empty:
> ...
> class Pair:
> ...
>
> (*) How to build a stack?
>
> These Lisp-like sequences are clearly a stack.

That is a very important observation. A Pair IS-A Stack(sort of).
If you had a stack you could create a Pair from it certainly.

> So far so good, but when it comes to building a better user interface
> for it I have no idea how to do it. I think one of the purposes of OOP
> is to organize code hierarchically so that we can reuse what we wrote.

One of the purposes of classes certainly. I'm not so sure it's a purpose
of OOP. They are not the same thing. A class is a programming construct
OOP is a programming style. Classes facilitate OOP but can be used
outside of OOP too.

> So I tried to make a Stack by inheriting Pair.

But you said above that a Pair was a Stack. Inheritance implies an
IS-A relationship, so Stack inheriting Pair would mean that a Stack
was a Pair. That is not really true.

A Stack could use a Pair (or many of them) but it is not a Pair.

Trying to use inheritance inappropriately is one of the
biggest (and commonest) mistakes in OOP. It invariably leads
to complications. If in doubt use delegation instead.

> class Stack(Pair):
> pass
>
>>>> Stack(1, Empty())
> Stack(1, Empty())
>
> Then I wrote pop and push.
>
>>>> Stack(1, Empty()).pop()
> 1
>
>>>> Stack(1, Empty()).push(2)
> Stack(2, Stack(1, Empty()))
>
> So far so good. Now let me show you what I can't do.
>
> (*) The difficulty of encapsulating a union
>
> The Lisp-like sequences we're building here are union-like data
> structures. A /sequence/ is either Empty() or Pair(..., /sequence/). I
> have not found a way to represent this either-or datastructure with a
> class. For example, there is no way right now to build an empty Stack
> by invoking the Stack constructor.
>
>>>> Stack()
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: Pair.__init__() missing 2 required positional arguments: 'first' and 'rest'
>

The usual Python approach to such things is to put some default
values(often None but could be an Empty instance in your case)
in the init() method parameter list. Then test if the inputs
are None and if so take the appropriate action.

> class Pair:
> def __init__(self, first=Empty(), rest=Empty()):

Like this.

> if not isinstance(rest, Pair) and not isinstance(rest, Empty):
> raise ValueError("rest must be Empty or Pair")
> self.first = first
> self.rest = rest
> def fromIterable(it):
> if len(it) == 0:
> return Empty()
> else:
> return Pair(it[0], Pair.fromIterable(it[1:]))
> def __str__(self):
> return "{}({!r}, {})".format(self.__class__.__name__, self.first, str(self.rest))
> def __repr__(self):
> return str(self)
> def __len__(self):
> return 1 + self.rest.__len__()
>
> class Empty:
> def __len__(self):
> return 0
> def __str__(self):
> return "Empty()"
> def __repr__(self):
> return self.__str__()
> def __new__(clss):
> if not hasattr(clss, "saved"):
> clss.saved = super().__new__(clss)
> return clss.saved
>
> class Stack(Pair):
> def pop(self):
> return self.first
> def push(self, x):
> return Stack(x, self)

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

Re: an oop question

<change-20221031133742@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20126&group=comp.lang.python#20126

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 31 Oct 2022 12:40:36 GMT
Organization: Stefan Ram
Lines: 20
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <change-20221031133742@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <SA1PR14MB585584E0C9313370167F2C2BB9379@SA1PR14MB5855.namprd14.prod.outlook.com> <mailman.843.1667174708.20444.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de UKw2gRUln/lpL91tP5g6Cw/Q7IJmnL9FVuOo+6PJNAyvoD
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Mon, 31 Oct 2022 12:40 UTC

"Weatherby,Gerard" <gweatherby@uchc.edu> writes:
>To answer your question generally, Union’s are not OO.

What's more non-OO to me here is immutability.

The functions/methods of the OP do not actually
change a stack but they return a new stack. This
style is being used in purely functional programming.

Object-oriented programming, however, uses objects
that have a state which may change in time. The whole
definition of a stack talks about how it is being
/modified/ by push and pop operations. So, I think that
object-oriented programming embraces change. At least
one can say that OOP by itself does not encourage
immutability even though sometimes one wants to have
immutability for some other reasons (for example,
immutability may help in parallel programming).

Re: an oop question

<LISP-20221031150239@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20128&group=comp.lang.python#20128

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 31 Oct 2022 14:14:57 GMT
Organization: Stefan Ram
Lines: 89
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <LISP-20221031150239@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <SA1PR14MB585584E0C9313370167F2C2BB9379@SA1PR14MB5855.namprd14.prod.outlook.com> <mailman.843.1667174708.20444.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de uihGvM8RYEzCAhgPefI0RgaCmd6wPs3bOlBsZi5hyiBFBN
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Mon, 31 Oct 2022 14:14 UTC

"Weatherby,Gerard" <gweatherby@uchc.edu> writes:
>I don’t understand your implementation enough to comment specifically. Wh=
>at’s the definition of Pair? (i.e. what methods and public attributes doe=
>s it have?) (I manage to escape Lisp as an undergrad)

When I learned LISP, it was still spelled "LISP". Below,
I am using the traditional LISP terms as I learned them,
while modern dialects may use different terms and names.

The peculiar usage of spaces is my own style and not
necessarily used by other LISP programmers.

A pair in LISP is the same as a pair in math or in English!

The low-level basic kind of a pair in LISP is called a
"dotted pair", because it is written as "( A . B )"
(to tell it from the list "( A B )", which is written
without a dot and is not the same as the dotted pair
"( A . B )").

A dotted pair is created with CONS, and one could take as
a definition the interrelation between CONS, CAD, and CDR,
which is:

( CAR( CONS A B )) is x, where x is the result of the evaluation of A
( CDR( CONS A B )) is y, where y is the result of the evaluation of B

. LISP uses a modified Cambridge notation by which the
application of the function f to the arguments x, y, z is
written as "( f x y z )" and not as "f( x, y, z )".

The evaluation of "( CONS A B )" yields the dotted pair
( x . y ), where
x is the result of the evaluation of A and
y is the the result of the evaluation of B.

Dotted pairs are used to build lists. For example, the
list (B A) is represented by

( B . ( A . NULL ))

where NULL is a special value used to mark the end of
a list. NULL can also be written as "()".

|
V
..---.---. .---.---.
| B | o----->| A | o---->|
'---'---' '---'---'

So,

( C . ( B A ))

is the list

( C B A )

|
V
..---.---. .---.---. .---.---.
| C | o----->| B | o----->| A | o---->|
'---'---' '---'---' '---'---'

. The terminating NULL is not shown in the list notation,
just as the terminating \0 is not shown for a C string.
But in dotted pair notation the last list is

( C .( B .( A . NULL )))

.

Application programmers in LISP usually would not think much
about the "lower tier" of dotted pairs that is used to implement
lists. So a pair of values in LISP usually would be implemented
by an application programmer as the list "( A B )", which internally
would be stored by the nesting of dotted pairs which is

"( A .( B . NULL ))"

|
V
..---.---. .---.---.
| B | o----->| A | o---->|
'---'---' '---'---'

.

Re: an oop question

<86h6zih8jb.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20138&group=comp.lang.python#20138

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!WY3w0uAbNvQ1bUHY2m4kXg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Tue, 01 Nov 2022 14:46:48 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86h6zih8jb.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
<mailman.848.1667193727.20444.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="56460"; posting-host="WY3w0uAbNvQ1bUHY2m4kXg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
Cancel-Lock: sha1:9LsDWInPi6rrjqOD6kkhKEOOiTI=
X-Notice: Filtered by postfilter v. 0.9.2
 by: Julieta Shem - Tue, 1 Nov 2022 17:46 UTC

Chris Angelico <rosuav@gmail.com> writes:

> On Mon, 31 Oct 2022 at 14:38, Julieta Shem <jshem@yaxenu.org> wrote:
>>
>> Chris Angelico <rosuav@gmail.com> writes:
>>
>> > The most straight-forward way to represent this concept in an
>> > object-oriented way is subclassing.
>> >
>> > class Stack:
>> > ... # put whatever code is common here
>> >
>> > class Empty(Stack):
>> > ... # put Empty-specific code here, possibly overriding Stack methods
>> >
>> > class Pair(Stack):
>> > ... # ditto, overriding or augmenting as needed
>> >
>> > This way, everything is an instance of Stack, but they are still
>> > distinct types for when you need to distinguish.
>>
>> Can you provide a small example? I can't see what you mean, but it
>> seems interesting.
>
> Sure. The easiest way would be to take your existing Empty and Pair
> classes, have them subclass Stack, and don't bother putting any code
> at all into Stack. Then construct an Empty and a few Pairs, and what
> you'll see is that all of them are also instances of Stack.
>
> After that, it's really a question of what you expect to be able to do
> with either an Empty or a Pair. Anything that should be possible with
> both types (that is, anything that should be possible with either
> variant of Stack) should get moved into the Stack type, while anything
> that is specific to one or the other stays in its own class. So here's
> a very very simple example:
>
> class Stack:
> def prepend(self, other):
> return Pair(other, self)
>
> class Empty(Stack):
> def is_last(self):
> return True
> def get_current(self):
> raise ValueError("Stack empty")
> def get_next(self):
> raise ValueError("Stack empty")
>
> class Pair(Stack):
> def __init__(self, item1, item2):
> self.item1 = item1
> self.item2 = item2
> def get_current(self):
> return self.item1
> def get_next(self):
> return self.item2
> def is_last(self):
> return isinstance(self.item2, Empty)
>
> With this setup, you can build a stack by prepending items onto an
> Empty endpoint, and can iterate over it with the get_current and
> get_next methods. (Making this actually iterable, so that it works
> with a Python 'for' loop, would be a good exercise.)
>
> In this example, there isn't much code in the Stack class. But you
> could easily add more, and it would apply to both Empty and Pair.

Thank you so much for the example. It's very interesting as it sort of
reverses my intuition. It seems non-obvious. I had in mind to build a
Stack out of Empty and Pair, but you seem to have done it the other way
around.

But I still don't see a way of using your classes up there in which I
have a single name to build empty and non-empty stacks. Let me
clarify. If I wish for an empty stack, I wish I could just say

>>> Stack()
Stack()

and if I wish for a nonempty stack, I'd write

>>> Stack(1, Stack(2, Stack(3, Stack())))
Stack(1, Stack(2, Stack(3, Stack())))

With your classes, I think I must write

>>> Empty() # That's an empty stack
....

>>> Pair(1, Pair(2, Empty())) # That's a non-empty stack
....

In other words, I need to memorize two different names for using stacks.
I'm trying to have a single name for both parts of the union (that is my
design of a stack).

Thanks so much!

Re: an oop question

<865yfyh7z5.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20139&group=comp.lang.python#20139

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!WY3w0uAbNvQ1bUHY2m4kXg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Tue, 01 Nov 2022 14:58:54 -0300
Organization: Aioe.org NNTP Server
Message-ID: <865yfyh7z5.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk>
<mailman.849.1667209022.20444.python-list@python.org>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="1489"; posting-host="WY3w0uAbNvQ1bUHY2m4kXg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
Cancel-Lock: sha1:ZJqEkiYP8j/zfuTeNTafD6cDCVI=
X-Notice: Filtered by postfilter v. 0.9.2
 by: Julieta Shem - Tue, 1 Nov 2022 17:58 UTC

Alan Gauld <learn2program@gmail.com> writes:

> On 30/10/2022 14:01, Julieta Shem wrote:
>
>> I wrote the classes
>>
>> class Empty:
>> ...
>> class Pair:
>> ...
>>
>> (*) How to build a stack?
>>
>> These Lisp-like sequences are clearly a stack.
>
> That is a very important observation. A Pair IS-A Stack(sort of).
> If you had a stack you could create a Pair from it certainly.

Yes, they are the same thing --- in my mind ---, except possibly for the
user interface, names and stuff. I do prefer to make the user think he
has something else simply because it has a different name. It is not
the user's business to know what things are on the inside.

>> So far so good, but when it comes to building a better user interface
>> for it I have no idea how to do it. I think one of the purposes of OOP
>> is to organize code hierarchically so that we can reuse what we wrote.
>
> One of the purposes of classes certainly. I'm not so sure it's a purpose
> of OOP. They are not the same thing. A class is a programming construct
> OOP is a programming style. Classes facilitate OOP but can be used
> outside of OOP too.

That's an interesting observation. I like that. Classes are one thing
and OOP is another. Of course, at the extreme I think I will get
nowhere in trying to detect in high-precision what is OOP and what is
not. The same for classes. I always liked to think of C structures as
some class. Instead of saying ``new Whatever()'', I'd say
``malloc(sizeof ...)''. I'd then have many procedures whose first
argument were a pointer to Whatever. They're the methods. So the
structure Whatever si the class itself. Is this use of C outside of
OOP? I say it is not because my notion of OOP is that --- a way to make
objects and have methods operate on them, changing them or not.

Should I allow the non-change of objects to be OOP as well? I think so.
To me what distinguishes functional from imperative is, for example,
imperative has side-effects. We can take an imperative set of tools and
do not produce any side-effects (locally speaking, of course) and that
would be indisguishable from functional programming. We can say that
imperative languages are more general than functional ones. (That's my
non-educated guess for the moment anyhow.)

>> So I tried to make a Stack by inheriting Pair.
>
> But you said above that a Pair was a Stack. Inheritance implies an
> IS-A relationship, so Stack inheriting Pair would mean that a Stack
> was a Pair. That is not really true.

That's another interesting observation. I do not have much
understanding of how to really think of these things and that's most
likely why I never tried to understand OOP or imperative programming.
It seems very difficult.

What I meant is that a Pair was a Stack and a Stack was a Pair. The
reason I was creating a Stack at all was just to make the user think
it's something different --- and with more obvious names for the case
under analysis, which was the use of a stack-like data structure.

> A Stack could use a Pair (or many of them) but it is not a Pair.

Is this how I should design it? I tried that, actually. It seemed to
complicate my life because I had to provide to my Stack class various
other methods my Pair class already had.

> Trying to use inheritance inappropriately is one of the
> biggest (and commonest) mistakes in OOP. It invariably leads
> to complications. If in doubt use delegation instead.

What is delegation?

I think that's why I never went into OOP and imperative languages. It
just seems bloody difficult to get anything right. Call me stupid or
what you will, but it seems very difficult.

Any book recomendations on getting this thing mathematics-clear?

Thank you!

Re: an oop question

<Stack-20221101191026@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20140&group=comp.lang.python#20140

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 1 Nov 2022 18:11:25 GMT
Organization: Stefan Ram
Lines: 33
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <Stack-20221101191026@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com> <mailman.840.1667169075.20444.python-list@python.org> <86v8o0hlno.fsf@yaxenu.org> <CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com> <mailman.848.1667193727.20444.python-list@python.org> <86h6zih8jb.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de SVRTUKNOIC0G3jruRf7C7gWh1lwH2/btyVNCvS1GcR5dXY
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Tue, 1 Nov 2022 18:11 UTC

Julieta Shem <jshem@yaxenu.org> writes:
>clarify. If I wish for an empty stack, I wish I could just say
>>>> Stack()
>Stack()
>and if I wish for a nonempty stack, I'd write
>>>> Stack(1, Stack(2, Stack(3, Stack())))
>Stack(1, Stack(2, Stack(3, Stack())))

If this is all,

main.py

class Stack:
def __init__( self, *args ):
self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else []
def __str__( self ):
if len( self.data ):
return f"Stack({self.data[0]}, {self.data[1]})"
else:
return f"Stack()"

print( Stack() )

print( Stack(1, Stack(2, Stack(3, Stack()))) )

output

Stack()
Stack(1, Stack(2, Stack(3, Stack())))

.

Re: an oop question

<OOP-20221101192258@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20141&group=comp.lang.python#20141

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 1 Nov 2022 18:28:14 GMT
Organization: Stefan Ram
Lines: 72
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <OOP-20221101192258@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <mailman.849.1667209022.20444.python-list@python.org> <865yfyh7z5.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de x2q7XWfZ8J7NBjYr6puLVg/Uw4R8Bqm2RxSTOOm/Gq5ZfL
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Tue, 1 Nov 2022 18:28 UTC

Julieta Shem <jshem@yaxenu.org> writes:
>Any book recomendations on getting this thing mathematics-clear?

OOP cannot be mathematics-clear because it is an /attempt/ to
abstract from several different programming languages.

When you ask Alan Kay (and I did!), the man who coined the term
"object-oriented", he will tell you (in my words):
"Object-oriented programming is possible in Smalltalk only.".

So, to get OOP crystal clear from the one who coined the
term, go ahead an learn Smalltalk!

But while Kay coined the term, many ideas of OOP are based
on Simula. So, you might think about learning Simula to get
the Dahl-flavor of OOP.

This is comp.lang.python. Here we do Python programming.

10 or 20 years ago there were still famous people, such as
Robert C. Martin, hanging around in "comp.object", and I would
have told you to go there, but today that newsgroup is deserted.

Here's an excerpt from an older post by me, written in May this year:

In 2003, I became aware of the fact that Alan Kay, the man
who coined the term "object-oriented programming" in 1967
(or in the temporal proximity of this year), never has given
a definition for it. I asked him via e-mail, and he kindly
responded. In that e-mail he also wrote something to the effect
that for him only Smalltalk allows object-oriented programming.
(On another occasion, he also said, "I invented the term Object-
Oriented and I can tell you I did not have C++ in mind.".) So,
I think that this point of view by Alan Kay is similar to what
Liam wrote about Smalltalk!

So, what did Alan Kay write to me in 2003? Here's the crucial excerpt:

|OOP to me means only messaging, local retention and protection and
|hiding of state-process, and extreme late-binding of all things. It
|can be done in Smalltalk and in LISP. There are possibly other
|systems in which this is possible, but I'm not aware of them.
Alan Kay, 2003

. I should add that the deepest insight I gained into what is the
actual point of OOP (as I wrote in my previous post in this thread)
I got from the writings of Robert C. Martin who clarified that
OOP makes it easy to add new types but hard to add new operations,
while procedural programming makes it easy to add new operations,
but hard to add new types.

|Procedural code (code using data structures) makes it easy to
|add new functions without changing the existing data
|structures. OO code, on the other hand, makes it easy to add
|new classes without changing existing functions.
Robert Cecil Martin

|Procedural code makes it hard to add new data structures
|because all the functions must change. OO code makes it hard
|to add new functions because all the classes must change.
Robert Cecil Martin

When one first reads this, it might not be obvious why this
is so spot on, but one can find this quotation in the book
"Clean Code" by Robert C. Martin and read more explanations
about it there.

Objects with data abstraction can already be found in CLU by
Barbara Liskov. But this is not yet OOP. The crucial feature
OOP adds to this is polymorphism ("late binding").

Re: an oop question

<Stack-20221101203308@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20142&group=comp.lang.python#20142

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 1 Nov 2022 19:34:50 GMT
Organization: Stefan Ram
Lines: 47
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <Stack-20221101203308@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <mailman.849.1667209022.20444.python-list@python.org> <865yfyh7z5.fsf@yaxenu.org> <OOP-20221101192258@ram.dialup.fu-berlin.de>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de BAVeJFbsb5X8sqyIYyLK/QvCghDP5vZHiPt56JpZddn+UE
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Tue, 1 Nov 2022 19:34 UTC

ram@zedat.fu-berlin.de (Stefan Ram) writes:
>The crucial feature OOP adds to this is polymorphism ("late binding").

If polymorphism is so crucial, the idea of subclasses
has something to it! So here's another way to code your
requirements, using subclasses:

main.py

class Stack:
def __new__( self, *args ):
return nonempty_stack( *args )if len( args ) else empty_stack()
def __str__( self ):
return str( self.data )

class nonempty_stack( Stack ):
def __new__( self, *args ):
return object().__new__( self )
def __init__( self, *args ):
self.data =[ args[ 0 ], args[ 1 ]]
def __str__( self ):
return f"Stack({self.data[0]}, {self.data[1]})"

class empty_stack( Stack ):
def __new__( self, *args ):
return object().__new__( self )
def __init__( self, *args ):
self.data = []
def __str__( self ):
return f"Stack()"

print( Stack() )
print( Stack(1, Stack(2, Stack(3, Stack()))) )

print()
print( type( Stack() ))
print( type( Stack(1, Stack(2, Stack(3, Stack()))) ))

output

Stack()
Stack(1, Stack(2, Stack(3, Stack())))

<class '__main__.empty_stack'>
<class '__main__.nonempty_stack'>

Re: an oop question

<mailman.858.1667334766.20444.python-list@python.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20144&group=comp.lang.python#20144

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: gweathe...@uchc.edu (Weatherby,Gerard)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Tue, 1 Nov 2022 20:32:33 +0000
Lines: 69
Message-ID: <mailman.858.1667334766.20444.python-list@python.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
<86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
<mailman.848.1667193727.20444.python-list@python.org>
<86h6zih8jb.fsf@yaxenu.org> <Stack-20221101191026@ram.dialup.fu-berlin.de>
<SA1PR14MB585551C6F43F9F22B4465941B9369@SA1PR14MB5855.namprd14.prod.outlook.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="Windows-1252"
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de R6lJZIrdc8GVta6UQQOuYgimWHGVgrfj081b/zvhEOww==
Return-Path: <prvs=0304bb9283=gweatherby@uchc.edu>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=uchc.edu header.i=@uchc.edu header.b=Jyrp5Qz4;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.003
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'def': 0.04; '2022': 0.05;
'okay': 0.07; 'ram': 0.07; 'else:': 0.09;
'received:namprd14.prod.outlook.com': 0.09; 'url-
ip:13.107.213.67/32': 0.09; 'url-ip:13.107.213/24': 0.09; 'url-
ip:13.107.246.67/32': 0.09; 'url-ip:13.107.246/24': 0.09;
'writes:': 0.09; 'url:mailman': 0.15; '***': 0.16; '>>>>': 0.16;
'email addr:zedat.fu-berlin.de&gt;': 0.16; 'email name:&lt;ram':
0.16; 'oop': 0.16; 'print(': 0.16; 'subject:oop': 0.16;
'url:urldefense': 0.16; 'url:v3': 0.16; 'subject:question': 0.17;
'to:addr:python-list': 0.20; 'all,': 0.20; "i'd": 0.24; 'to:name
:python-list@python.org': 0.24; 'url:listinfo': 0.25; 'opening':
0.26; 'received:edu': 0.26; 'skip:{ 20': 0.26; 'stefan': 0.26;
'else': 0.27; 'output': 0.28; 'email addr:python.org&gt;': 0.28;
'question': 0.32; 'empty': 0.32; 'python-list': 0.32; 'header:In-
Reply-To:1': 0.34; 'header:Received:8': 0.36; 'received:filterd':
0.37; 'received:pps.filterd': 0.37; 'class': 0.37; 'url-
ip:13.107/16': 0.38; 'could': 0.38; 'date:': 0.39; 'use': 0.39;
'charset:windows-1252': 0.60; 'email.': 0.61; 'from:': 0.62;
'to:': 0.62; 'gives': 0.62; 're:': 0.64; 'wish': 0.66; 'url-
ip:52.6/16': 0.69; 'skip:f 20': 0.75; 'clicking': 0.76; 'links.':
0.81; 'attention:': 0.84; 'email name:&lt;python-list': 0.84;
'it\x92s': 0.84; 'skip:& 50': 0.84; 'stack,': 0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=uchc.edu;
h=from : to : subject :
date : message-id : references : in-reply-to : content-type :
mime-version; s=UCHC03162020;
bh=oMbLn1pSWH5dtN6hx4Ut2/MzrHzZybNLMC0zHXo9SAs=;
b=Jyrp5Qz4aMTSBNMb4760d1pBWIxi28B4itqvb41fBPtvCEs3qbKq3TsA5p+rwuJbcmlO
114xL0Pi/vXegTRDTJyYE9Ed8H7v37zhvKE4J2HC4iMT5CRM6EZ1dZ5hEEXFqqtlcc/V
z6qSQdNwZ0zZ0isvdXqaNMfyqOywxDOXPcWI8JjK4ZLBA8e86jfqsHkkYYw+dJUxwpCo
Wske1/uhdHOn3lHOIQVFF+yRJjaHKlxIYhvFISu38FIs1oWLKddcLViDUw9bvSStM0zs
vf9A+R9kHeB6e97JcVPnMUxRPBklNQwfJMDDKtzuQ8obXD0AFfSLjLDNf7tu96+UjS9+ xA==
ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none;
b=lD0FEXH01CCcAOwM5CbdRVoRhk0GOCEnQPURolU8r2YtgkIqqWhaYZiUTtuNPApBhfDifh/JpXI/tFOQaJUG7aLr3E6EDPEUQUW7ivP4aE/R8jM0qsQ23SHhwoTPvjWYZ7s+raaIpSdmK2REcpAopfIXNF7xEhqvI4QJhJqsJE/yuiCtelNcqkqqTmye5XpOzq5yiRDGk6xC4+fghKr3nZCeMuvt00yBksc4sNzoW7c8FE5T6juZdVvnktqV9WX0NbqmznoLKDWd9TKs1gDrDDq/BVht8pfvZS/F9aTR5dzNg49VBhhmDXymnzf/a5RWyUIkRdMujDW6ryrbQfeAiw==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com;
s=arcselector9901;
h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1;
bh=oMbLn1pSWH5dtN6hx4Ut2/MzrHzZybNLMC0zHXo9SAs=;
b=kUCoaqvesmGdqRPoD/srQ5o1cF7X6VPZykO84F+fsTmkxsZSHLmgwxD75NHXqdev0NCDuEoGSHdhBH1FHnQnSHgTjzNx1D3afafJG3GXoNoSshOcU+ezUQ36wKmnf0Sg87ev+ygXTGGKL0FqSo94U8LsawLxLsXHGYIB0DwLGkDl23EHca1EbHjHv3Yj65bSWQeRcfhJlDMTBOrzGup4MYmKQR9hcG53G16lxhWgWD+iMOdP2UQ41BEQgw5ZXHahnM0eV7c2NqwRRnQSxIh2lTnwg+dUOSRMDHciAB+IOiCSAHK8Y6lOR7jwXAAwvJmH/Ie6WbizDu72CjtFye9oJA==
ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass
smtp.mailfrom=uchc.edu; dmarc=pass action=none header.from=uchc.edu;
dkim=pass header.d=uchc.edu; arc=none
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=uchc.onmicrosoft.com;
s=selector2-uchc-onmicrosoft-com;
h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-SenderADCheck;
bh=oMbLn1pSWH5dtN6hx4Ut2/MzrHzZybNLMC0zHXo9SAs=;
b=dlVx8F/wbpzIAieozlx91jEoMJgpSC8AF1pGP5pcvvgZXP1SFSo41BbzszKs5MC3yVVBnSDysHZF51Kaw3KF8hnRvVdyCbxZCezIkVzA13VqlGcb7qYqIEtOMSzRpksK5KIME/g20/G+ShmRJLohF1zk6gKVjj8awZ2Y3PWOvxY=
Thread-Topic: an oop question
Thread-Index: AQHY7KnGzJyfzLrp/k2CwYYqO+x3r64ne0DNgAADFT+AAAbrgIAAVhCJgAAcu4CAAoL4qYAAAAg5gAAM27s=
In-Reply-To: <Stack-20221101191026@ram.dialup.fu-berlin.de>
Accept-Language: en-US
Content-Language: en-US
X-MS-Has-Attach:
X-MS-TNEF-Correlator:
x-ms-publictraffictype: Email
x-ms-traffictypediagnostic: SA1PR14MB5855:EE_|DM6PR14MB3824:EE_
x-ms-office365-filtering-correlation-id: d2303a01-bce1-45ce-479c-08dabc4834b0
x-ms-exchange-senderadcheck: 1
x-ms-exchange-antispam-relay: 0
x-microsoft-antispam: BCL:0;
x-microsoft-antispam-message-info: L5garoywwpTudBe2dx/whXBP2C3khmJXZJWw9k9T0S8llg5sapYlVMkLfXuW/trRfUl4F7LlhyTrfXUocjYAP2Sbu/8CgngbC2AU+V6bbJtAxEFPsYqSmxX0bK6/PSseQp5cVmDmP8PWoQXEo7B7aAZ0w/ENXfy8xahn9haX0l10Xz2dxaH7438Mc37WQ1EDcGk1ZD9M2zPdS2U4nRKcAIss/f61iIJm2nnNl0guw93bDglaAbi6FQQs5RW4sl+GW1nXxVC/pBXAppV43Q3Iwoek68SJnqsSPc/LKw9ig7UXAWvXbC8zRAp3XrV3liG1pLA82ZIbS1SeVPjOjH/0NQvkbcUmvbBM1V7xzjFliAWEoscjJ6KjvA7cdoWKOIpt53Pu19d98C9yCJ0MPSJYHJkx1ln3wPoMhDATmSWrUGO89nVWGWmnqBz2fgWOD56nkfRA6mwKg9VWgW8d7VaUlRN+UfNqHRn3QjYqaVQ+zWQF0kwaMezy9rd1+aw9IvYqR9Lkhrd4AIzUemGq6AhiQaeebTGuoOUsSj3lDiTy+EkwKY8bJdwV3dKXn1/dNj9BX7Y7hDY/m5B0YnecHM+16Tq28EmLehHJ9sJ2WkCk4HU4Waa/lUEr4uFsmvNohbaQQv3/s98SmnJcr80614eQz7Ddd+DFx6o6pJoqquWcYB00hq8ebyUvhQt4shtbFKgZHwC5kpNKMiGbbEOSqyfUfyZr3qhwYbIjqttfzee4zADrR1mvz+ens5d+72Q93xhm02CluTXOSXwd4vIgy7AbRtkfUOj+CsLsgELHWN95PmM=
x-forefront-antispam-report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:;
IPV:NLI; SFV:NSPM; H:SA1PR14MB5855.namprd14.prod.outlook.com; PTR:; CAT:NONE;
SFS:(13230022)(136003)(39850400004)(366004)(376002)(346002)(396003)(451199015)(186003)(86362001)(2906002)(41320700001)(38070700005)(966005)(71200400001)(122000001)(55016003)(166002)(478600001)(6506007)(75432002)(7696005)(26005)(9686003)(53546011)(91956017)(8936002)(66946007)(52536014)(6916009)(7116003)(76116006)(66476007)(316002)(41300700001)(8676002)(66556008)(5660300002)(64756008)(38100700002)(3480700007)(33656002)(66446008)(786003);
DIR:OUT; SFP:1101;
x-ms-exchange-antispam-messagedata-chunkcount: 1
x-ms-exchange-antispam-messagedata-0: TupkNbhOJcV95Vb/ioSe4h7IFtN4B3RFkkgp/pItlKHFgZD2u/l3UkIx
9gLMsjKwFedHr/+GFVSgoYzU9dPvSa6kjyfGJNcx91krMEp+9KUQqpC+
DKfr+3hQkCmZv489PSaR6V3iagXhM1Uqeji2BXXLdw5+5yajGYV3Yuc/
SYsqWZy/xe1z97wc/tKuabR1ylpbJSKTlnFutmCleAxkFiW1bhxlYrUw
aqqt3pwE7FFgnnfxT/b4r0mkWeLRT9KLTvwDjDAGgDAM/cFrn7wjsxw6
ct95BtSJ+153IzqtCLctDSeNyJYbdGW3xufBK/BiY05GH+Mm5yydO8mr
8p8sTJY64Rf0atKfkrbUwLbQa2PCacqsyLiv2uVOm1scKVK/r0UuBjEG
2a7BeaIVs95WavYnDFwNrx6J4CiiAr+J+Wc63aGSTfeZB++6gaQ+N0jD
mD66hT+zSVYkxy/3rA1PvgTHH1A7DLYlBryjYPGrh92i/4CbBpDaxSA2
DEIzvXCaKWWNmnCB9qJQADD9xREUoXD1Af30O05PHxZHEOG5wFPMUnVn
irBdDzZ8yAmQC21k8Duux/MzGOnsgitw5gTRWawrdMbG8duHXD0sunLq
/1ZAx/noyWzg1yecrvgAf2gVAYTVknOkGPrmeABBYguTA0dPyu+MMDj8
qYSMW1QHeKCFXkvf+/wQeTq8JVUuiWPLzyfULXimvuL/X6Prg7YVVqMi
32IyUp1CzbM8uV3S6tvcaEPC9a4ppLzI4tFf4mWfnZ8ReRl/9McVtNEx
Zn5gmT3CltiU8SiYHxldzBhfE0wc2zjuZgal24NadvJd4j0dQOZfPFgQ
ooX5xzQm9V1KyZTBBC0D4XccCe4HlBko4JFQobsApKy45FG/6jxXfsz/
bQR7l7j2L09g/Utfds93oR35Gk8FrVsKyelOgXoe7F4Tjup/EkCKRKQ8
HMSySVVjZZxJrhVYmNFiQTotLcpQ9baKmewUC8voqZKomxHs2SNQWCC5
ZHHcE9PXxnnVUGzrb8cH4nflxKdpIUsDAM4Ou0tNZMORgYd6o9sRXahi
WqkQ/0Jq/8Ntnm7xCjIg/TQocdC6zliO60chPhZIMjXMF48FD2TmISlE
EK178H5BFJvL43URMTLYNRqiGswt8N5JjOlki0j9fv1h7rHS+agkXjFZ
ssmf5AlcwI7O9yHd32gGq0kRULMkb2ty6+azbS+780/9OCKMsWlqKFfx
tlu+Jd4aAaUtWV/84JyOOTDXq2AjMs5UwseI0R3mpADhXh1VcaR/yJPL
GCamBIAsPGTG2OIWABQPEnp0J3LuQm5Nz04tospBhwRCJtaoRhq9DwDw
B6Cza0Rdh1797sK8H3dNiD+nghUT/53evMRpyIZwZLCYUD5RmWjfTJ1K
B3+zUTVH7Qwbh4Bqv1bmLznO2+kxAJrfHykm4cQVGmsuu1MhkmMpZdpR
DgSCTXZFMoxXRSKmdaQThIIuBP72D30PCg2icux3FMFx2xJc5rhTUugo
loDeq/rCg3nUs7neZ6wYNGX0hc38cQLRdtdZ4Liof96xgnKt/kr0Vk+G
WcOsubDDdq+Rt19c3wnr53YBpC2pybmyVP0juq+79HGEV744Ss+RCA
==
X-MS-Exchange-CrossTenant-AuthAs: Internal
X-MS-Exchange-CrossTenant-AuthSource: SA1PR14MB5855.namprd14.prod.outlook.com
X-MS-Exchange-CrossTenant-Network-Message-Id: d2303a01-bce1-45ce-479c-08dabc4834b0
X-MS-Exchange-CrossTenant-originalarrivaltime: 01 Nov 2022 20:32:33.3669 (UTC)
X-MS-Exchange-CrossTenant-fromentityheader: Hosted
X-MS-Exchange-CrossTenant-id: 5c82d83a-818a-4c16-b540-ded2344a7ad3
X-MS-Exchange-CrossTenant-mailboxtype: HOSTED
X-MS-Exchange-CrossTenant-userprincipalname: ctXJ7AWBU+79ghK695h8ZHTOqfS1IppNkxwFaUeWzEY29bjwQGd2dNrd8hY4rjQRaHaLEa/vVyFZUZY6fR6o8w==
X-MS-Exchange-Transport-CrossTenantHeadersStamped: DM6PR14MB3824
X-Proofpoint-GUID: Z_rbRozT4iFpoQJrT0rL1SW5Ke0Cn6H1
X-Proofpoint-ORIG-GUID: Z_rbRozT4iFpoQJrT0rL1SW5Ke0Cn6H1
X-Proofpoint-Virus-Version: vendor=baseguard
engine=ICAP:2.0.205,Aquarius:18.0.895,Hydra:6.0.545,FMLib:17.11.122.1
definitions=2022-11-01_10,2022-11-01_02,2022-06-22_01
X-Proofpoint-Spam-Details: rule=outbound_notspam policy=outbound score=0
malwarescore=0 suspectscore=0
bulkscore=0 mlxlogscore=999 impostorscore=0 lowpriorityscore=0
priorityscore=1501 mlxscore=0 phishscore=0 spamscore=0 adultscore=0
clxscore=1015 classifier=spam adjust=0 reason=mlx scancount=1
engine=8.12.0-2210170000 definitions=main-2211010145
X-Content-Filtered-By: Mailman/MimeDel 2.1.39
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <SA1PR14MB585551C6F43F9F22B4465941B9369@SA1PR14MB5855.namprd14.prod.outlook.com>
X-Mailman-Original-References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
<86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
<mailman.848.1667193727.20444.python-list@python.org>
<86h6zih8jb.fsf@yaxenu.org> <Stack-20221101191026@ram.dialup.fu-berlin.de>
 by: Weatherby,Gerard - Tue, 1 Nov 2022 20:32 UTC

I think:

class Stack:
def __init__( self, *args ):
self.data = args

def __str__( self ):
return f"Stack({','.join(str(x) for x in self.data)})"

gives equivalent output for the if len(args) is 0 or 2, if it’s okay for self.data to be a tuple.

class Stack:
def __init__( self, *args ):
self.data = list(args)

def __str__( self ):
return f"Stack({','.join(str(x) for x in self.data)})"

If it’s desired self.data be a list.

From: Python-list <python-list-bounces+gweatherby=uchc.edu@python.org> on behalf of Stefan Ram <ram@zedat.fu-berlin.de>
Date: Tuesday, November 1, 2022 at 3:43 PM
To: python-list@python.org <python-list@python.org>
Subject: Re: an oop question
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

Julieta Shem <jshem@yaxenu.org> writes:
>clarify. If I wish for an empty stack, I wish I could just say
>>>> Stack()
>Stack()
>and if I wish for a nonempty stack, I'd write
>>>> Stack(1, Stack(2, Stack(3, Stack())))
>Stack(1, Stack(2, Stack(3, Stack())))

If this is all,

main.py

class Stack:
def __init__( self, *args ):
self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else []
def __str__( self ):
if len( self.data ):
return f"Stack({self.data[0]}, {self.data[1]})"
else:
return f"Stack()"

print( Stack() )

print( Stack(1, Stack(2, Stack(3, Stack()))) )

output

Stack()
Stack(1, Stack(2, Stack(3, Stack())))

.

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!itEYnwU5jJ0z8_rkW_q_ogw3ZJUNdHdMNkMLpSAqBdozBNrr7NqPs_gNsbx8W9uXRLZpG38C9an17Yx2zUf-mSA$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!itEYnwU5jJ0z8_rkW_q_ogw3ZJUNdHdMNkMLpSAqBdozBNrr7NqPs_gNsbx8W9uXRLZpG38C9an17Yx2zUf-mSA$>

Re: an oop question

<86sfj2fl9u.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20146&group=comp.lang.python#20146

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!WY3w0uAbNvQ1bUHY2m4kXg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Tue, 01 Nov 2022 17:54:37 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86sfj2fl9u.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de>
<86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
<mailman.848.1667193727.20444.python-list@python.org>
<86h6zih8jb.fsf@yaxenu.org>
<Stack-20221101191026@ram.dialup.fu-berlin.de>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="18291"; posting-host="WY3w0uAbNvQ1bUHY2m4kXg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
Cancel-Lock: sha1:eriBR0SB1+wwIcUuFJ/ii1uBfFE=
X-Notice: Filtered by postfilter v. 0.9.2
 by: Julieta Shem - Tue, 1 Nov 2022 20:54 UTC

ram@zedat.fu-berlin.de (Stefan Ram) writes:

> Julieta Shem <jshem@yaxenu.org> writes:
>>clarify. If I wish for an empty stack, I wish I could just say
>>>>> Stack()
>>Stack()
>>and if I wish for a nonempty stack, I'd write
>>>>> Stack(1, Stack(2, Stack(3, Stack())))
>>Stack(1, Stack(2, Stack(3, Stack())))
>
> If this is all,
>
> main.py
>
> class Stack:
> def __init__( self, *args ):
> self.data = [ args[ 0 ], args[ 1 ]]if len( args ) else []
> def __str__( self ):
> if len( self.data ):
> return f"Stack({self.data[0]}, {self.data[1]})"
> else:
> return f"Stack()"
>
> print( Stack() )
>
> print( Stack(1, Stack(2, Stack(3, Stack()))) )
>
> output
>
> Stack()
> Stack(1, Stack(2, Stack(3, Stack())))

Thanks! But we've left behind a more basic requirement --- the Stack
class wishes for all the methods already written in some class called
Pair, which has a certain connection with a class Empty. This
requirement has been implicit in the first message in this thread,
though. I didn't make it explicit. (In other words, this part of the
thread only makes sense by taking into account all the previous messages
up in the thread.)

Re: an oop question

<86leoufl6e.fsf@yaxenu.org>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20147&group=comp.lang.python#20147

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!WY3w0uAbNvQ1bUHY2m4kXg.user.46.165.242.91.POSTED!not-for-mail
From: jsh...@yaxenu.org (Julieta Shem)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Tue, 01 Nov 2022 17:56:41 -0300
Organization: Aioe.org NNTP Server
Message-ID: <86leoufl6e.fsf@yaxenu.org>
References: <86y1sxmmvo.fsf@yaxenu.org>
<39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk>
<mailman.849.1667209022.20444.python-list@python.org>
<865yfyh7z5.fsf@yaxenu.org>
<OOP-20221101192258@ram.dialup.fu-berlin.de>
<Stack-20221101203308@ram.dialup.fu-berlin.de>
Mime-Version: 1.0
Content-Type: text/plain
Injection-Info: gioia.aioe.org; logging-data="18291"; posting-host="WY3w0uAbNvQ1bUHY2m4kXg.user.gioia.aioe.org"; mail-complaints-to="abuse@aioe.org";
X-Notice: Filtered by postfilter v. 0.9.2
Cancel-Lock: sha1:H6k6G0CNkUrUv/BfHNj0+KA60QE=
 by: Julieta Shem - Tue, 1 Nov 2022 20:56 UTC

ram@zedat.fu-berlin.de (Stefan Ram) writes:

> ram@zedat.fu-berlin.de (Stefan Ram) writes:
>>The crucial feature OOP adds to this is polymorphism ("late binding").
>
> If polymorphism is so crucial, the idea of subclasses
> has something to it! [...]

I wonder what Rich Hickey would say here. Didn't he design Clojure with
``multimethods'' so that we can get some kind of polymorphism without
subclassing?

Re: an oop question

<jseftvFndmlU1@mid.individual.net>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20150&group=comp.lang.python#20150

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!usenet.goja.nl.eu.org!3.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail
From: greg.ew...@canterbury.ac.nz (Greg Ewing)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: Wed, 2 Nov 2022 19:10:05 +1300
Lines: 53
Message-ID: <jseftvFndmlU1@mid.individual.net>
References: <86y1sxmmvo.fsf@yaxenu.org>
<unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org>
<86leoxi5i7.fsf@yaxenu.org>
<CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com>
<mailman.840.1667169075.20444.python-list@python.org>
<86v8o0hlno.fsf@yaxenu.org>
<CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com>
<mailman.848.1667193727.20444.python-list@python.org>
<86h6zih8jb.fsf@yaxenu.org> <Stack-20221101191026@ram.dialup.fu-berlin.de>
<86sfj2fl9u.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: individual.net iUxRkFrPWsZQf2Ddu2nSDwC+QA1G+qDdLtIvObrNxCXBZ7mfqc
Cancel-Lock: sha1:1Lo9zrd9/snlcXk1HZ5i23Ab9/k=
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:91.0)
Gecko/20100101 Thunderbird/91.3.2
Content-Language: en-US
In-Reply-To: <86sfj2fl9u.fsf@yaxenu.org>
 by: Greg Ewing - Wed, 2 Nov 2022 06:10 UTC

On 2/11/22 9:54 am, Julieta Shem wrote:
> But we've left behind a more basic requirement --- the Stack
> class wishes for all the methods already written in some class called
> Pair,

Is that *really* what you want, though?

To my way of thinking, a Stack and a Pair are quite different
data structures, each having their own characteristic operations.

Things I want to be able to do with a Stack:
- Create an empty stack
- Push an item onto the top of the stack
- Pop an item off the top of the stack

Things I want to be able to do with a Pair:
- Create a pair containing two given objects
- Get the first item
- Get the second item

I don't see any overlap between these at the conceptual level.
Possibly I might want to use Pairs as part of the *implementation*
of a stack, but that doesn't mean that any Pair methods should
appear as Stack methods.

Here's how I might do this in a functional style using Python:

class Pair:
def __init__(self, first, second):
self._first = first
self._second = second
def first(self):
return self._first
def second(self):
return self._second

class Stack:
def __init__(self):
self._data = None
def push(self, item):
result = Stack()
result._data = Pair(item, self._data)
return result
def pop(self):
rest = Stack()
rest._data = self._data.second()
return self._data.first(), rest

Note that neither Stack nor Pair inherits from the other.

--
Greg

Re: an oop question

<Stack-20221102095636@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20151&group=comp.lang.python#20151

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!aioe.org!news.uzoreto.com!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 2 Nov 2022 09:02:02 GMT
Organization: Stefan Ram
Lines: 68
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <Stack-20221102095636@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <unions-20221030153013@ram.dialup.fu-berlin.de> <86k04hmkf3.fsf@yaxenu.org> <86leoxi5i7.fsf@yaxenu.org> <CAPTjJmqibdNc+ehd7=Hc1w5ypHCpJpYjZd1_oMinHE6pu6Ax0Q@mail.gmail.com> <mailman.840.1667169075.20444.python-list@python.org> <86v8o0hlno.fsf@yaxenu.org> <CAPTjJmpa=FMqeidpZReL3NXjua8MdUHi4jPe_z6jUf_k+6s9VA@mail.gmail.com> <mailman.848.1667193727.20444.python-list@python.org> <86h6zih8jb.fsf@yaxenu.org> <Stack-20221101191026@ram.dialup.fu-berlin.de> <86sfj2fl9u.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de MY33P+/cKcll0ON4hEz2EQBDu59/vBJ8jSIIYKkhbnNfLl
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Wed, 2 Nov 2022 09:02 UTC

Julieta Shem <jshem@yaxenu.org> writes:
>Thanks! But we've left behind a more basic requirement --- the Stack
>class wishes for all the methods already written in some class called
>Pair, which has a certain connection with a class Empty. This
>requirement has been implicit in the first message in this thread,
>though. I didn't make it explicit. (In other words, this part of the
>thread only makes sense by taking into account all the previous messages
>up in the thread.)

Sorry! So, I combine the "Stack" class from my other post with
your two classes "Pair" and "Empty":

main.py

class Stack:
def __new__( self, *args ):
return Pair( args[ 0 ], args[ 1 ])if args else Empty()

class Pair:
def __init__(self, first, rest):
if not isinstance(rest, Pair) and not isinstance(rest, Empty):
raise ValueError("rest must be Empty or Pair")
self.first = first
self.rest = rest
def fromIterable(it):
if len(it) == 0:
return Empty()
else:
return Pair(it[0], Pair.fromIterable(it[1:]))
def __str__(self):
return "{}({!r}, {})".format(self.__class__.__name__, self.first, str(self.rest))
def __repr__(self):
return str(self)
def __len__(self):
return 1 + self.rest.__len__()

class Empty:
def __len__(self):
return 0
def __str__(self):
return "Empty()"
def __repr__(self):
return self.__str__()
def __new__(clss):
if not hasattr(clss, "saved"):
clss.saved = super().__new__(clss)
return clss.saved

print( Stack() )
print( Stack(1, Stack(2, Stack(3, Stack()))) )

print()
print( type( Stack() ))
print( type( Stack(1, Stack(2, Stack(3, Stack()))) ))

output:

Empty()
Pair(1, Pair(2, Pair(3, Empty())))

<class '__main__.Empty'>
<class '__main__.Pair'>

You also could have inherit them from "Stack",
but then they would need a custom __new__ method
with "return object().__new__( self )".

Re: an oop question

<inheritance-20221102100538@ram.dialup.fu-berlin.de>

  copy mid

https://www.novabbs.com/devel/article-flat.php?id=20152&group=comp.lang.python#20152

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: ram...@zedat.fu-berlin.de (Stefan Ram)
Newsgroups: comp.lang.python
Subject: Re: an oop question
Date: 2 Nov 2022 09:07:28 GMT
Organization: Stefan Ram
Lines: 16
Expires: 1 Sep 2023 11:59:58 GMT
Message-ID: <inheritance-20221102100538@ram.dialup.fu-berlin.de>
References: <86y1sxmmvo.fsf@yaxenu.org> <39be3c02-df6e-5aa3-2220-55c403aabc43@yahoo.co.uk> <mailman.849.1667209022.20444.python-list@python.org> <865yfyh7z5.fsf@yaxenu.org> <OOP-20221101192258@ram.dialup.fu-berlin.de> <Stack-20221101203308@ram.dialup.fu-berlin.de> <86leoufl6e.fsf@yaxenu.org>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Trace: news.uni-berlin.de WqQAfWiDyfeq/FzX0FL4qwehLPXfY6zIXAPcG+dX9J6O8Q
X-Copyright: (C) Copyright 2022 Stefan Ram. All rights reserved.
Distribution through any means other than regular usenet
channels is forbidden. It is forbidden to publish this
article in the Web, to change URIs of this article into links,
and to transfer the body without this notice, but quotations
of parts in other Usenet posts are allowed.
X-No-Archive: Yes
Archive: no
X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some
services to mirror the article in the web. But the article may
be kept on a Usenet archive server with only NNTP access.
X-No-Html: yes
Content-Language: en-US
Accept-Language: de-DE, en-US, it, fr-FR
 by: Stefan Ram - Wed, 2 Nov 2022 09:07 UTC

Julieta Shem <jshem@yaxenu.org> writes:
>ram@zedat.fu-berlin.de (Stefan Ram) writes:
>>ram@zedat.fu-berlin.de (Stefan Ram) writes:
>>>The crucial feature OOP adds to this is polymorphism ("late binding").
>>If polymorphism is so crucial, the idea of subclasses
>>has something to it! [...]
>I wonder what Rich Hickey would say here. Didn't he design Clojure with
>``multimethods'' so that we can get some kind of polymorphism without
>subclassing?

Yes. In general, one can have polymorphism without subclassing, but
in class-based OOP, such as in Python, inheritance is the standard
way to enable polymorphism. In other languages, such as Clojure, Self,
or the original JavaScript, one might use other means than inheritance.

Pages:123
server_pubkey.txt

rocksolid light 0.9.81
clearnet tor