【发布时间】:2021-07-06 20:24:12
【问题描述】:
我是 OOP 的新手,并通过编写预算类来练习:
class Budget:
category_record = []
def __init__(self, category = '', balance = 0):
self.category = category
self.balance = balance
Budget.category_record.append(self)
def deposit(self, amount):
self.balance += amount
print(f"You have deposited {amount} into your {self.category} Budget, your balance is {self.balance}")
return
def withdraw(self, amount):
if amount > self.balance:
print('Insufficient Balance, unable to withdraw')
else:
self.balance -= amount
print(f"You have withdrawn {amount} from your {self.category} Budget, your balance is {self.balance}")
return
def category_balance(self):
print(f'Your balance is {self.balance} for your {self.category} budget')
IM试图将预算类的所有实例记录为一种方法(如果我的条款有误,请原谅我,仍然习惯它们)
# Instantiate Food budget
food = Budget('food')
# deposit 200 into food budget
food.deposit(200)
# withdraw 100 from food budget
food.withdraw(100)
#instantaite rent budget
rent = Budget('house', 5000)
# check balance of rent budget
rent.category_balance()
这样,当我在预算类上调用记录方法时,我可以获得 ['food', 'rent'] 的列表 或者如果可能的话,一个字典,键为类别,值为 balance {'food':100...}
【问题讨论】:
-
看来您走在了正确的轨道上。您想创建一些
@classmethod方法来访问存储在您的category_record列表中的Budget对象。 -
嘿,我很好奇你为什么要跟踪预算实例?
标签: python class object oop instance