Object in List : how?

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Mon Jul 25 00:28:30 EDT 2022


On 2022-07-24 at 19:47:38 -0500,
Khairil Sitanggang <ksit70 at gmail.com> wrote:

> Regarding [Peter Otten's] comment : "
> *However, usually object creation and initialization iscombined by allowing
> arguments to the initializer:*" , so which one of the two classes Node1,
> Node2 below is more common in practice? Option 2, I guess.

No.  Please use option 1.

Another option would be to expose b as an optional parameter with a
default value:

    class Node:
        def __init__(self, a, b=0):
            self.a = a
            self.b = self.calculation() if b == 0 else b

There are other ways to write that particular assignment to b (because
the default is 0), but the relevant concept for right now is that
callers *can* supply a value for b, but that they don't *have* to:

    n1 = Node(a) # uses a default value for b
    n2 = Node(a, 22) # overrides the default; use 22 instead

Designing APIs can be tricky, and it's not an exact science.


More information about the Python-list mailing list