繁体   English   中英

类和实例

[英]Classes and Instances

我是 OOP 的新手,并通过编写预算 class 来练习:

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试图记录预算class的所有实例作为一种方法(如果我的条款有误,请原谅我,仍然习惯它们)


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

这样,当我在预算 class 上调用记录方法时,我可以获得 ['food', 'rent'] 的列表,或者如果可能的话,可以获得一个字典,其中键为类别,值为余额 {'food':100... }

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

根据您的问题,我假设您希望将该方法称为record 最好的方法是使用带有内置classmethod装饰器的 class 方法。 这些方法作用于 class 本身,而不是实例,因此采用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)

详细说明我的@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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM