如何解决Python:如何从外部函数更改类内部函数的值
嗨,我正在展示我的代码的一部分。我在对象类(CashOnCashROI)中创建了一个函数(propertyValue)。然后我在课外创建了一个函数(计算器)。我将类实例化为“rental”,然后尝试使用rental.propertyValue() 在类外调用propertyValue 函数。
我想要做的是从计算器() 函数中更改“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???
解决方法
修改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???
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。