Python:如何从外部函数更改类内部函数的值

2024-10-01 19:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在展示我的代码的一部分。我在对象类(CashOnCashROI)中创建了一个函数(propertyValue)。然后我在类外创建了一个函数(计算器)。我将该类实例化为“rental”,然后尝试使用rental.propertyValue()在类外部调用propertyValue函数

我试图做的是更改calculator()函数中“self.globValue=int(value)”的值,但我一直得到:TypeError:propertyValue()接受1个位置参数,但给出了2个。我希望有人能帮我解释发生了什么,如何修复它,以及是否有更好的方法?我刚刚开始学习课程,所以我非常感激

这是代码,它应该给出相同的TypeError

class CashOnCashROI:      
    def propertyValue(self):
        value = input('How much will you pay for the property? \n')
        while value.isdigit() == False:
            value = input('Sorry, we need a number? What is the proposed property value? \n')
        print(f"Your current purchase value for the property is: {value}")
        self.globValue = int(value)

def calculator():
    rental = CashOnCashROI()
    while True:
        rental.propertyValue()
        choice = input('<Other parameters asked here>, "Value" to change the property value.\n')
        if choice.lower() == "value":
            xvalue = input('What would the new property value be? \n')
            rental.propertyValue(xvalue) ### How do I change the value here???

Tags: the函数代码selfinputvaluedefproperty
1条回答
网友
1楼 · 发布于 2024-10-01 19:23:03

修改propertyValue函数: 设置新参数(值)允许将函数外部的值作为参数传递,并跳过输入函数。如果未提供值,请使用旧的实现:

class CashOnCashROI:      
    def propertyValue(self, value=None):
        if not value:
            value = input('How much will you pay for the property? \n')
            while value.isdigit() == False:
                value = input('Sorry, we need a number? What is the proposed property value? \n')
            print(f"Your current purchase value for the property is: {value}")
        self.globValue = int(value)

def calculator():
    rental = CashOnCashROI()
    while True:
        rental.propertyValue()
        choice = input('<Other parameters asked here>, "Value" to change the property value.\n')
        if choice.lower() == "value":
            xvalue = input('What would the new property value be? \n')
            rental.propertyValue(xvalue) ### How do I change the value here???

相关问题 更多 >

    热门问题