【问题标题】:How to only ask for variable one time when intializing a class multiple times (python) [duplicate]多次初始化一个类时如何只要求一次变量(python)[重复]
【发布时间】:2021-10-27 03:56:59
【问题描述】:
inc_inp = 0
class Budget:
    def __init__(self,inc_inp = 0):
        if inc_inp < 1:
            self.monthly_income = int(input("Enter monthly income after taxes: "))
            inc_inp += 1



    def deposit(self, dep_amt):
        pass
    
    def withdraw(self, wth_amt):
        pass


class Wants(Budget):
    def __init__(self):
        super().__init__()
        print(self.monthly_income)

class Needs(Budget):
    def __init__(self):
        super().__init__()
        print(self.monthly_income)

inc = Needs()
inc2 = Wants()
inc3 = Needs()

这给出了结果: 输入税后月收入:2000 2000 输入税后月收入:2000 2000 输入税后月收入:2000 2000 (我进入2000)

我正在尝试找出一种方法,只在类初始化时请求一次monthly_income(我知道 if 语句不起作用,因为每次初始化类时它都设置为 0,它只会让我问题更清楚一点) 我希望能够在我的子类中使用月收入,而不必从父类运行特定方法(如果这有意义吗?!)非常感谢任何建议

【问题讨论】:

  • 抱歉输出的格式,应该把它放在代码部分。堆栈溢出仍然是新的。也拼错了退出大声笑
  • 在类初始化时已经询问过一次。您正在初始化该类 3 次,因此它会询问 3 次。
  • @TigerhawkT3 是的,但是是否可以只要求一次并让子类在初始化时继承输入? (即使不是直接可行的,有没有好的解决方法?
  • 这是XY Problem。您不需要任何解决方法,您需要重新考虑您的整个方法。从毫无用处的全局inc_inp 到同样毫无意义的inc_inp += 1 以及创建不做任何事情的新实例,我想说您必须回到您的教学材料并查看课程和范围的工作方式.
  • 你可以让budget的init获取varmonthly_income并将其设置为属性,然后在实例对象之前询问monthly_income。里面有那个变量

标签: python oop parent-child


【解决方案1】:

您可以将inc_inp 设为类变量,这样它将在所有类/子类实例之间共享。

class Budget:

    inc_inp = 0

    def __init__(self, inc_inp=0):
        if Budget.inc_inp < 1:
            Budget.monthly_income = int(input("Enter monthly income after taxes: "))
            Budget._inc_inp += 1

    def deposit(self, dep_amt):
        pass

    def withdraw(self, wth_amt):
        pass


class Wants(Budget):
    def __init__(self):
        super().__init__()
        print(self.monthly_income)


class Needs(Budget):
    def __init__(self):
        super().__init__()
        print(self.monthly_income)


if __name__ == '__main__':
    inc = Needs()
    inc2 = Wants()
    inc3 = Needs()

输出

Enter monthly income after taxes: 6
6
6
6

【讨论】:

  • 多实例几乎肯定不是一开始的方式。
  • 我不明白为什么会这样。为什么 self.monthly_income 是一样的?
  • @UlisesBussi - 这就是变量名的查找方式。如果找不到具有该名称的实例变量,它将检查具有该名称的类变量。
猜你喜欢
  • 2015-08-23
  • 2016-04-29
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2023-03-19
相关资源
最近更新 更多