Creating objects within an existing object in Python
我想创建一个对象,在其内部保存和创建不同的对象。我有一个外部阶级和内部阶级,像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Outer: def __init__(self, name): self.name = name def sayHello(self): print"Hello" + self.name class Inner1: def __init__(self, name): self.name = name class Inner2(Inner1): pass class Inner3(Inner1): pass new = outer("new") |
然后需要对inner2或inner3的对象进行新的处理…我和
老实说,内部类通常不是一个好主意,尤其是在"包含"类之外实例化它们时。
但是为了回答您的问题,基本上内部类只是在一个不同的范围内声明的,所以您需要引用它所在的范围。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # Changed to a capitol letter as that is more conventional class Outer: name ="" def __init__(self, name): self.name = name def sayHello(self): print ("Hello" + self.name) class Inner1: def __init__(self, name): self.name = name class Inner2(Inner1): pass class Inner3(Inner1): pass newOuter = Outer("newOuter") newInner2 = Outer.Inner2("newInner2") |
下面是如何嵌套类和嵌套实例化的方法。在嵌入类时,只嵌入类型。您必须在EDCOX1中创建实例0
(如果您尝试在所有外部实例之间共享全局内部实例,请更新您的问题。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Outer(object): class Inner1(object): pass class Inner2(Inner1): pass class Inner3(Inner2): pass def __init__(self): self.inner1 = Outer.Inner1() self.inner2 = Outer.Inner2() self.inner3 = Outer.Inner3() outer = Outer() print outer.inner1 print outer.inner2 print outer.inner3 |
请注意,您不必为此实际使用嵌套类——您的类可以在类外部定义,并且有时更倾向于作为更简单、更pythonic的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Inner1(object): pass class Inner2(Inner1): pass class Inner3(Inner2): pass class Outer(object): def __init__(self): self.inner1 = Inner1() self.inner2 = Inner2() self.inner3 = Inner3() outer = Outer() print outer.inner1 print outer.inner2 print outer.inner3 |
有时你也会看到…
1 2 3 4 5 | class Inner1(object): pass class Outer(object): Inner1 = Inner1 |
对类内的类进行"方便"的引用。这通常与类可能抛出的自定义异常一起使用。
对于嵌套类是否是首选,有许多不同的意见。