我写了下面的代码,试图弄清楚如何在主类中实例化子类。我想出了一些感觉不对的东西。至少对我来说是这样。
这种实例化有什么问题吗?有没有更好的方法来调用子类?
class Family():
def __init__(self):
self.Father = self.Father(self)
self.Mother = self.Mother(self)
class Father():
def __init__(self, instance = ''):
self = instance if instance != '' else self
print self
def method(self):
print "Father Method"
def fatherMethod(self):
print "Father Method"
class Mother():
def __init__(self, instance = ''):
self = instance if instance != '' else self
print self
def method(self):
print "Mother Method"
def motherMethod(self):
print "Mother Method"
if __name__ == "__main__":
Family = Family()
Family.Father.method()
Family.Mother.method()
请您参考如下方法:
您定义的不是(至少在 Python 术语中)子类 - 它们是内部类或嵌套类。我猜这实际上不是您想要实现的目标,但我不确定您真正想要的是什么 - 但这是我的四个最佳猜测:
A subclass是从另一个类继承的类称为子类的地方。要使
father成为family的子类,请使用语法class Father(Family):。您在这里创建的实际上称为内部类,而不是子类。当您看到类似
Family.Father.method()的内容时,通常意味着 Family 是一个 module Father 是该模块中的一个类。在 Python 中,module基本上意味着.py 文件。模块没有__init__方法,但是模块顶层的所有代码(例如if __name__ ...行)都会在模块执行时执行是进口的。同样,您可以将 Family 设置为 package - 在 Python 中,这基本上意味着文件系统上的一个目录,其中包含一个
__init__.py文件。Father和Mother将成为包中的模块或类可能您要实现的目标是声明类型为
Family的对象始终有一个Father对象和一个Mother对象。这不需要嵌套类(事实上,嵌套类是一种完全奇怪的方法)。只需使用:
>>> class Mother(): ... def whoami(self): ... print "I'm a mother" ... >>> class Father(): ... def whoami(self): ... print "I'm a father" ... >>> class Family(): ... def __init__(self): ... self.mother = Mother() ... self.father = Father() ... >>> f = Family() >>> f.father.whoami() I'm a father >>> f.mother.whoami() I'm a mother >>>
