[Tutor] Inheritance in Python
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Sep 10 09:47:41 EDT 2020
On 10/09/2020 13:46, Manprit Singh wrote:
> half adder is a combinational logic circuit , which can generate Sum and
> Carry output for 2 input bits . Table given below describes the output of
> half adder
>
> Inp1 Inp2 SUM Carry
> 0 0 0 0
> 0 1 1 0
> 1 0 1 0
> 1 1 0 1
>
> It is clear from the table that SUM bit is generated with bitwise
> Exclusive OR and Carry bit is generated with bitwise AND .
>
> So coming to the question, IF there are two classes one for bitwise AND
> and second for bitwise Exclusive OR operation. and i have to make a class
> for half adder , if i am not wrong i can use inheritance for deriving a
> new class for half adder from existing classes of bitwise AND and Bitwise
> OR operation.
>
> Need your guidance .
>
Everything is possible but not everything is a good idea.
Inheritance is intended to reflect the concept of an "is-a"
relationship. So subclasses should have the same interface
as the superclass (possibly with some extensions).
So the question is: Does a half adder look like an xor or
and gate to the user? Is the interface similar. Could you
use them interchangeably? Insofar as they both have two
inputs yes, but the gates only have one output whereas
the half-adder has 2.
There is another form of structure in OOP, namely composition.
Is it not more accurate to say that the half-adder *contains*
an and gate and an xor gate?
I appreciate that you are using concepts with which you are
familiar to learn about OOP. However the problem with these
logic gate examples is that they are really just functions.
You can write a function that returns the logical result of
two (or more) inputs and it would be just as effective as
a class - and no need to create instances.
def AND(*in): return all(in)
def XOR(x,y): return x^y # multiple inputs is trickier.
def half_adder(x,y): return (XOR(x,y),AND(x,y)
sum,carry = half_adder(1,1)
Classes are best used for things that have state - consider
a bistable, or latching or FIFO buffer, or similar component.
There the output depends on the previous inputs.
Gates can be represented as objects if you were building say
a CAD system with multiple components joined together. Then
you might want to store references to the connected components
and pass the output signals into these. But that is quite a
complex simulation to write since you need to add clocks etc.
--
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