class Bill。
def __init__(self,type,imount):
self.amount = amount
self.type = type: self.amount = amount.
def total(*args)。
total_bill = []
for arg in args:
total_bill.append(arg.amount)
return sum(total_bill)
b1 = Bill('Elect',500)
b2 = Bill('煤氣',300)
b3 = 賬單('其他',100)
print(Bill.total(b1,b2,b3))
print(b1.total(b2))
我正試圖理解Python的OOP邏輯。在這里,我創建了一個方法(total)來計算賬單物件的總金額。這段代碼可以作業,但似乎很不尋常,因為第二個列印(b1.total(b2))是無意義的(當我把它作為一個實體的方法呼叫時)。因此,我想知道這是否會是一個體面的方法?我的意思是在類中的實體之間創建一個計算方法? 什么是獲得票據總和的最好方法。(賬單的數量可能會更多。
uj5u.com熱心網友回復:
你可以使用一個類變數來保存所有的賬單專案,然后在計算總數時使用這個變數,而不是將專案作為引數傳遞。
class Bill:
all_bills = []
def __init__(self,type,a amount):
self.amount = amount
self.type = type: self.金額 = amount.
self.all_bills.append(self)
@classmethod
def total(cls)。
return sum(arg.amount for arg in cls.all_bills)
b1 = Bill('Elect',500)
b2 = Bill('煤氣',300)
b3 = 賬單('其他',100)
print(Bill.total())
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310471.html
標籤:
