2010-01-07 162 views
1

我写了下面的代码,试图找出如何实例化主类中的子类..我想出了一些感觉不正确的东西..至少对我而言。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() 
+0

这看起来很奇怪。为什么你将自我传递给内部类构造函数?请解释你想用这个做什么。 – 2010-01-07 10:10:12

回答

6

您定义的内容有而不是(至少在Python术语中)子类 - 它们是内部类或嵌套类。我猜,这是不是其实是你所想达到的,但我不知道你是真正想要的东西 - 但这里是我的四个最好的猜测:

  1. A subclass是类继承哪里从另一个类被称为子类。要使father成为family的一个子类,请使用语法class Father(Family):。你在这里创建的实际上被称为内部类,而不是子类。

  2. 当你看到像Family.Father.method()这样的东西时,通常意味着家庭是module而父亲是该模块中的一个类。在Python中,module基本上表示.py file。模块没有__init__方法,但模块顶层的所有代码(例如if __name__ ...行)都会在导入模块时执行。

  3. 同样,你可以使家庭成为package--在Python中基本上是指文件系统上包含__init__.py文件的目录。然后FatherMother将包

  4. 也许你想达到什么样的声明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 
>>> 
+0

我很好奇 - 你瞄准了哪些? – 2010-01-07 10:37:29

1

你是对的,这个代码不感觉权。我的问题是...

  • 你想达到什么目的?没有必要在Family内定义FatherMother,它们可以在Family之外定义并聚合到它中。 (是不是FatherMother不应该在Family之外被访问?Python没有可见性修饰符,例如因为一个原则:'我们都在这里成长',这意味着开发者应该负责并且承担代码的负责处理...)

  • 你真的需要像Class.Class.method这样的东西吗?除此之外,这种方法查找代价有点昂贵,这些链可能表明错误的轴,这意味着您试图从一个不是非常清晰的设计点抓住功能(抱歉在这里模糊不清)。

1

Blergh。

为什么父亲和母亲嵌套在家庭?没有理由这样做。在外面定义它们,然后在里面实例化它们。

我不确定你想要做什么。你可能想看看Descriptors,这是一种定义clss内的子对象的方法。