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.
I have trouble understanding the Connector
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
tgate.setNextPin(self)
def getFrom(self):
return self.fromgate
def getTo(self):
return self.togate
The method setNextPin
defined in BinaryGate(LogicGate)
has an input of source
. But when it is being accessed in Connector
class, we are not giving a second argument. So how can it be implemented even without giving all the arguments.
Also, how can the setNextPin
method in Connector
class understand that it can access the method defined for it in BinaryGate
class?
I tried had to figure it out but I couldn't. Can someone help me understand this.
答案 0 :(得分:0)
你在这里缺少两件事:隐含的函数参数和鸭子打字。
首先,语法tgate.setNextPin(self)
调用函数setNextPin(tgate, self)
。第一个参数是调用该方法的对象(通常名为self)。您感到困惑,因为我们将self
作为 second 参数传递给函数setNextPin
,但该函数的第一个参数也称为self
。这是一个范围问题,这两个self
引用不同的参数(取决于您所在的函数)。
其次,有鸭子打字。该函数如何知道它可以访问BinaryGate
类中的方法?它根本不知道!所有函数都知道它希望tgate
属于具有方法setNextPin
的类型。如果这是BinaryGate
或任何其他对象,则无关紧要。如果传递的对象没有调用此方法,那么Python将在运行时失败,因为它将无法找到要调用的函数setNextPin
。