2017-04-13 226 views
1

我是新來的蟒蛇,我想知道這是否可能:孩子和父母對象

我想創建一個對象並附加到它的另一個對象。

OBJECT A 
    Child 1 
    Child 2 
OBJECT B 
    Child 3 
    Child 4 
    Child 5 
     Child 6 
      Child 7 

這是可能的嗎?

+1

你是什麼意思「它連接到另一個對象」呢? – sgrg

+1

簡短的回答是肯定的。正確的答案是:你想做什麼,你認爲這將解決?這聽起來像一個[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – TemporalWolf

+0

我們可以想象一個非常簡單的問題。我有一個對象:一輛汽車。我要創建其中的兩個,一個是紅色的,一個是藍色的。之後,我將創建8個輪胎(每輛車4輛),並配有不同重量的輪胎。最後我想知道藍色車和紅色車的4個輪胎的重量。 – Ralk

回答

1

要跟隨你的榜樣:

class Car(object): 
    def __init__(self, tire_size = 1): 
     self.tires = [Tire(tire_size) for _ in range(4)] 

class Tire(object): 
    def __init__(self, size): 
     self.weight = 2.25 * size 

現在你可以製作汽車並查詢輪胎的重量:

>>> red = Car(1) 
>>> red.tires 
[<Tire object at 0x7fe08ac7d890>, <Tire object at 0x7fe08ac7d9d0>, <Tire object at 0x7fe08ac7d7d0>, <Tire object at 0x7fe08ac7d950>] 
>>> red.tires[0] 
<Tire object at 0x7fe08ac7d890> 
>>> red.tires[0].weight 
2.25 

您可以根據需要改變結構,以更好的方式(如果所有的輪胎都是一樣的)是隻指定tirenum_tires

>>> class Car(object): 
    def __init__(self, tire): 
     self.tire = tire 
     self.num_tires = 4 
>>> blue = Car(Tire(2)) 
>>> blue.tire.weight 
4.5 
>>> blue.num_tires 
4 
4

如果你談論的是面向對象的條款,當然可以,你不解釋清楚,你想做的事,但兩件事情浮現在我的腦海裏,如果你談論的是OOP是:

  • 如果您正在討論繼承,您可以在創建子類時使子對象擴展父對象:class child(parent):
  • 如果您正在討論對象組合,只需使子對象成爲父對象的isntance變量,作爲構造變量傳遞它
0

下面是一個例子:

在這種情況下,對象可以是一個人而不是一名員工,但是作爲一名員工,他們必須是一個人。爲此Person類是父母給員工

這裏的鏈接到一篇文章,說真的幫助我理解繼承: http://www.python-course.eu/python3_inheritance.php

class Person: 

    def __init__(self, first, last): 
     self.firstname = first 
     self.lastname = last 

    def Name(self): 
     return self.firstname + " " + self.lastname 

class Employee(Person): 

    def __init__(self, first, last, staffnum): 
     Person.__init__(self,first, last) 
     self.staffnumber = staffnum 

    def GetEmployee(self): 
     return self.Name() + ", " + self.staffnumber 

x = Person("Marge", "Simpson") 
y = Employee("Homer", "Simpson", "1007") 

print(x.Name()) 
print(y.GetEmployee())