【问题标题】:Classes and Instances类和实例
【发布时间】: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


【解决方案1】:

详细说明我的@classmethod 评论:

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')

    @classmethod
    def budget_list(cls):
        if len(Budget.category_record)== 0:
            print("No budgets created")
        else:
            print("Budget Categories:")
            for budge in Budget.category_record:
                print(budge.category)

    @classmethod
    def full_report(cls):
        if len(Budget.category_record)== 0:
            print("No budgets created")
        else:
            print("Budget Balances:")
            for budge in Budget.category_record:
                print(f"{budge.category} : {budge.balance}")




# 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()

Budget.budget_list()

Budget.full_report()

【讨论】:

    【解决方案2】:

    如果您想获取 Budget 类的所有实例的列表,您的方法可以只返回 category_record 列表,您已经在其中存储了所有创建时的实例。但是,您似乎希望列表包含要分配实例的变量的名称(标识符)。 Budget 类将无法访问这些名称,因此,我建议您尝试使用类别名称,因为这将记录在您的 category_record 变量中。

    根据您的问题,我假设您希望将该方法称为record。最好的方法是使用带有内置 classmethod 装饰器的类方法。这些方法作用于类本身,而不是实例,因此采用cls 参数而不是self 参数(这两个名称都只是约定,但是我强烈建议不要偏离约定,因为它会使您的代码对其他人来说不必要地复杂)。例如:

    class Budget:
        ...
        # other code
        ....
        category_record = []
    
        @classmethod
        def record(cls):
            return [budget.category for budget in cls.category_record]
            # If you are unfamiliar with this syntax, search up "list comprehensions"
    
    # Access the list
    print(Budget.category_record)
    

    如果你想要一个字典,你可以用这个替换那个方法:

    class Budget:
        ...
        # other code
        ...
        category_record = []
    
        @classmethod
        def record(cls):
            return {budget.category:budget.balance for budget in cls.category_record}
            # If you are unfamiliar with this syntax, search up "dictionary comprehensions"
    
    # Access the dictionary
    print(Budget.category_record)
    

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 2013-09-28
      相关资源
      最近更新 更多