Object in List : how?

dn PythonList at DancesWithMice.info
Mon Jul 25 02:01:10 EDT 2022


On 25/07/2022 12.47, Khairil Sitanggang wrote:
> Regarding your 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.
> Thanks,
> 
> 
> # option 1:
> class Node1:
>     def __init__(self, a):
>         self.a = a
>         self.b = self.calculation()
> 
>     def calculation(self):
>         r = self.a + 10
>         return r
> 
> # option 2:
> class Node2:
>     def __init__(self, a, b):
>         self.a = a
>         self.b = b
> 
>         self.b = self.calculation()
> 
>     def calculation(self):
>         r = self.a + 10
>         return r
> 
> nd1 = Node1(10)
> nd2 = Node2(10, 0) # 0 is dummy, will be overwritten by the call to
> calculation()

Let's start with calculation() - even though it is not your specific
question:

Given that "self" makes it into an instance-method, it will have access
to self.b! Accordingly, the intermediate variable "r" and its return
serves no purpose - assuming calculation() is only used to produce a
value for self.b - which would leave:

    def calculation( self ):
        self.b = self.a + 10

At which point, the method becomes pointless - may as well put its
single line in-line within __init__() - as I say, with above assumptions.


Some languages do expect that every identifier (data-attribute in this
case) be declared (as to type) and probably also initialised with a
value. Some languages, and some Style Guides require that all
data-attributes are declared within the constructor/initialiser.

Python requires neither of these.

Accordingly, if the "b" argument will only ever be a "dummy", there is
absolutely no need for it - indeed one could argue that its presence is
confusing because it gives the impression than it could assume any
value. (see elsewhere in this thread).

So, with assumptions and short of facts, "option 1" seems better (with
the additional consideration regarding calculation(), as above).
-- 
Regards,
=dn


More information about the Python-list mailing list