Python 实例化子类
我写了下面的代码,想弄明白怎么在主类里面创建子类的实例。结果我写出来的东西让我觉得不太对劲,至少对我来说是这样。
这种创建实例的方法有什么问题吗?有没有更好的方式来调用子类呢?
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()
2 个回答
你说得对,这段代码看起来不太对劲。我想问几个问题……
你想要实现什么呢?其实在
Family
里面定义Father
和Mother
并不是必要的,它们可以在Family
外面定义,然后再放到Family
里面。是不是因为Father
和Mother
不应该在Family
外部被访问?在Python里没有可见性修饰符,比如说有个原则是:“我们都是成年人了”,意思是开发者应该对自己的代码负责,合理使用代码……你真的需要像
Class.Class.method
这样的写法吗?除了方法查找稍微耗费资源之外,这种链式调用可能意味着你在从一个设计不太清晰的地方去获取功能(抱歉我说得有点模糊)。
你所定义的其实不是(至少在Python的术语中)子类,而是内部类或嵌套类。我猜这可能不是你真正想要的结果,但我不太确定你想要什么。不过,我可以给你四个我最好的猜测:
子类是指从另一个类继承的类。要让
father
成为family
的子类,你可以用这样的语法:class Father(Family):
。你这里创建的实际上是一个内部类,而不是子类。当你看到像
Family.Father.method()
这样的东西时,这通常意味着 Family 是一个 模块,而 Father 是这个模块中的一个类。在Python中,模块
基本上就是指一个.py 文件
。模块没有__init__
方法,但模块顶层的所有代码(比如if __name__ ...
这一行)在模块被导入时会被执行。同样,你可以把 Family 变成一个 包——在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 >>>