這很難理解你想從你的帖子中獲得什麼,但是我會試着給你舉例說明我的認爲你正在嘗試去做。
讓我們從僅關注Box
-class開始,現在忽略Item
。 這裏是你擁有的一切:
class Box():
id = 0
def __init__(self,id):
Box.id = id
def __get__(self):
return Box.id
的__get__
方法是沒有用的,根本就不在這裏使用它,你不需要它。 現在我們注意到,您是否設置了Box.id = 0
,這意味着您可以撥打print(Box.id)
並打印0
。 您也可以初始化一個新盒子實例,並且您可以撥打print(box_instance.id)
,這也將按預期打印0
。
但是,在您的__init__
方法中,您更改Box.id
而不是實例自己的ID,這是您的意思?下面是關於將與您的代碼發生什麼一個簡單的例子:
In: Box.id
Out: 0
a = Box(1)
In: a.id
Out: 1
In: Box.id
Out: 1
b = Box(2)
In: b.id
Out: 2
In: a.id
Out: 2
In: Box.id
Out: 2
正如你可以看到這裏(或測試自己),初始化新Box
對象時,它改變的Box
類的ID,而不是實例的ID 。 這樣,如果您初始化新的Box
-instance,則每個實例的id都會更改。 這是由於它實際上不是實例的id,而是它的編號Box
。
如果這是您想要的行爲,請隨時使用它(您仍然不需要__get__
),但是如果您希望每個Box都有其唯一的ID,請使用self
而不是框。現在
class Box:
id = 0 # This is Box class' id, it's not even necessary to define it
def __init__(self, id): # This will be each instance's unique id
self.id = id #self.id means the instance's unique id
,我們得到了Box
差不多完成,我們可以開始對Item
工作。 我很不確定你試圖用這個做什麼,但看看你的代碼,看起來好像你實際上試圖給每個項目一個唯一的ID(這是一個好主意),然後你想給他們box_id
這簡直就是Box.id
,這個班'id本身? 這對我沒有任何意義。
我實際上認爲你想實現的目標:將項目插入框中,這樣你就想讓項目知道它是「父」框的ID。它可以做如下:
class Item: #Notice how inheriting is not needed at all!!
def __init__(self, id, parent):
self.id = id
self.parent = parent
# I prefer calling it parent, call it what ever you want, box works too
現在我也建議,就是:
- 裏面
Box.__init__()
,定義一個列表self.items = []
- 裏面
Item.__init__()
,追加self
於母公司的項目。 self.parent.items.append(self)
這樣你的物品就知道他們在的箱子,箱子知道箱子裏有哪些物品。
編輯:如何使用父簡單例子代碼:
box1 = Box(1) #box1 has id of 1
box2 = Box(2) #box2 has id of 2
item1 = Item(3, box1) #item1 has id of 3, parent box1
item2 = Item(4, box2) #item2 has id of 4, parent box2
item3 = Item(5, box1) #item3 has id of 5, parent box1
In: item1.id
Out: 3
In: item1.parent.id
Out: 1
In: item2.id
Out: 4
In: item2.parent.id
Out: 2
In: item3.id
Out: 5
In: item3.parent.id
Out: 1
In: item3.parent == item1.parent
Out: True
我們在這裏看到,項目就可以直接調用它的父的方法和使用它的屬性。 這樣,您可以在一個方框中包含多個項目((item1
和item3
均具有相同的父項),並且這些項目的每個項目的parent
屬性都指向該方框。
基本上item1.parent == box1
所以item1.parent.id
就是你在你的代碼中調用的item.box_id
。
與你所說的相反,'Item'不是'Box'的子類 – NPE
另外,你可以擴展一點,你實際上試圖用這個 – NPE
項目縮進,不是它使它是一個子類? – Thiru