RTM RTM - 3 months ago 31x
Python Question

Object oriented programming: IS-A vs HAS-A relationships?

I am learning about object oriented programming from

Problem solving with Algorithms and Data structures

book using the online version available on interactive python website. Link is mentioned below.

Object Oriented Programming

I have trouble understanding the
class that is mentioned in the above link. What exactly is the difference between IS-A and HAS-A relationship?

class Connector:

def __init__(self, fgate, tgate):
self.fromgate = fgate
self.togate = tgate


def getFrom(self):
return self.fromgate

def getTo(self):
return self.togate

The method
defined in
has an input of
. But when it is being accessed in
class, we are not giving a second argument. So how can it be implemented even without giving all the arguments.

Also, how can the
method in
class understand that it can access the method defined for it in

I tried had to figure it out but I couldn't. Can someone help me understand this.


You are missing two things here: implied function parameters and duck typing.

Firstly, the syntax tgate.setNextPin(self) calls the function setNextPin(tgate, self). The first parameter is the object for which the method is being called (usually named self). You are getting confused because we are passing self as the second parameter to the function setNextPin but the first parameter of that function is also called self. This is a scoping issue, those two selfs refer to different parameters (depending on which function you are in).

Secondly, there is duck typing. How does the function know it can access the method in the BinaryGate class? It doesn't know that at all! All the function knows is that it expects tgate to be of a type that has a method setNextPin. It doesn't matter if this is a BinaryGate or any other object. If the object passed doesn't have this method to call then Python will fail at run time as it will be unable to find the function setNextPin to call.