[Tutor] Formal parameter in starred form
Manprit Singh
manpritsinghece at gmail.com
Tue Sep 8 12:46:15 EDT 2020
Dear sir ,
Kindly consider a function written for AND gate.
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 :
def andgate(*p):
return int(all(p))
andgate(1, 1, 1) # This function call will give output = 1 as all inputs
are 1
andgate(1, 0, 1) # This function call will give output = 0 as all inputs
are not 1
andgate(1, 1, 1, 1, 1) # This function call will give output = 1 as all
inputs are 1
First 2 calls are accepting 3 inputs and the 3rd call is accepting 5 inputs
. So
this function definition can be used for any number of inputs, this is due
to *p
as a formal parameter, which receives a tuple.
Now my question is, the same concept( starred formal parameter ) can be
applied in classes also or not ?
For more clarity i am writing code for same AND gate class as follows :
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
Using same class for 6 inputs :
------------------------------------------
and1 = AndGate(1, 1, 0, 1, 0, 1)
print(and1.output) # will give output as 0
and1.inputs(1, 1, 1, 1, 1, 1)
print(and1.output) # will give output as 1
Regards
Manprit Singh
More information about the Tutor
mailing list