首页 > 解决方案 > 如何在同一类中使用来自不同方法的变量而不将其作为参数?

问题描述

我有一个名为“save”的类,它是“budget”类的子类。我有一个名为 save 的变量,我想在“save”类的多个方法中使用它。

这是代码块:

class save(budget):

    def show(self):
        print('you have this much money to save:')
        saving = saving+(self.money * 0.4)
        print(saving)

    def spend(self):
        saved = int(input('How much have you set aside to save from this paycheck?'))
        saving = saving-saved
        print('This is how much you need to save: '+str(self.money))

我也更喜欢不使用关键字 global 的解决方案。

标签: python

解决方案


正如@TomKarzes 正确概述的那样,这是如何执行此操作的说明:

class save(budget):

    def __init__(self):
        super().__init__()
        self.saving = 0

    def show(self):
        print('you have this much money to save:')
        self.saving = self.saving+(self.money * 0.4)
        print(self.saving)

    def spend(self):
        saved = int(input('How much have you set aside to save from this paycheck?'))
        self.saving = self.saving-saved
        print('This is how much you need to save: '+str(self.money))

关于您的代码的一件事,假设这是您期望的逻辑......您的方法每次调用时都会show()更改变量的值。self.saving我不希望从具有该名称的方法中获得这一点,所以我想知道您的意思是不是:

def show(self):
    print('you have this much money to save:')
    print(self.saving+(self.money * 0.4))

推荐阅读