我正試圖弄清楚如何在Python中訪問另一個類的實體。
在下面的例子中,我創建了兩個類,house和paint,我想把house類中的尺寸作為paint類中的一個變數:
class house。
def __init__(self, length, width)
self.length = length
self.width = width
class paint。
def __init__(self, color_paint, price)。
self.color_paint = color_paint
self.price = price * (length * width) # <-- length and width from class house
uj5u.com熱心網友回復:
你可以將一個House類的實體傳遞給Paint類的初始化器:
class House。
def __init__(self, length, width)。
self.length = length
self.width = width
class Paint。
def __init__(self, color_paint, price, house)。
self.house = house
self.color_paint = color_paint
self.price = price * (self.house.length * self.house.width)
house_obj = House(4, 5)
paint_obj = Paint('blue', 1000, house_obj)
print(paint_obj.price)
輸出 :
20000 # which is 4 * 5 * 1000
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/307310.html
標籤:
上一篇:驗證在SQL中添加一個相同的記錄
