[Tutor] Formal parameter in starred form
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Sep 8 16:55:49 EDT 2020
On 08/09/2020 17:46, Manprit Singh wrote:
> AND gate is a logic gate whose output is 1 if all of the inputs of the
> logic gate are 1, else the output is 0. The function written below will
> return an output of an AND gate, and is capable of accepting any number of
> inputs :
It seems odd to be using 1 and 0 when Python supports a boolean
type giving values of True and False. That way you avoid any
need to convert to int...
> Now my question is, the same concept( starred formal parameter ) can be
> applied in classes also or not ?
Short answer is yes. Methods are functions like any other in that
respect. The only difference is the automatic binding of self to an
object. But in terms of their definition they are just like a normal
function.
> class AndGate:
>
> def __init__(self, *p):
> self.inputs(*p)
>
> @property
> def output(self):
> return int(all(self.a))
>
> def inputs(self, *a):
> self.a = a
>
> Using class AndGate for 3 inputs :
> ----------------------------------
> and1 = AndGate(1, 1, 0)
> print(and1.output) # will give output as 0
> and1.inputs(1, 1, 1)
> print(and1.output) # will give output as 1
Since you have written the code I assume you tried it?
Therefore you already know that it works... That is after all
what the >>> prompt is for - to test things out.
So presumably what you really want to know is whether this is an
acceptable Python idiom? The answer is yes and fairly common at that.
--
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
More information about the Tutor
mailing list