Python更改__init__中声明的变量值 [英] Python changing variable values declared in __init__
问题描述
我很犹豫地问这个问题,但我的头似乎无法绕过 class
, __ init __()
和 str
的使用.希望某人有足够的耐心回答可能是一个非常愚蠢的问题.我写了以下内容以测试我的理解(= 0)"
I hesitate to ask this question, but my head cannot seem to get around the use of class
, __init__()
, and str
. Hoping that someone will be patient enough to answer what is probably a very dumb question.
I have written the following to test my understanding ( = 0)"
class Test():
def __init__(self,var1,var2):
self.__var1 = var1
self.__var2 = var2
def change_var1(self):
self.__var1
self.__var1 =2*self.__var1
return self.__var1, self.__var2
def change_var2(self):
self.__var2
self.__var2 = self.__var2*2
return self.__var1, self.__var2
def __repr__(self):
return "var1 is {}, and var 2 = {}".format(self.__var1, self.__var2)
t = Test(4,"Bye")
print(t.change_var1 )
print(t.change_var2)
我无法在 init 中声明的变量由后续函数更改.我假设我错误地使用了类 init str__.运行上面的命令的响应是:
I cannot get the variables declared in init to be changed by the subsequent functions. I assume that I have used class, init, str__ incorrectly. The response to running what I have above is:
<bound method Test.change_var1 of var1 is 4, and var 2 = Bye>
<bound method Test.change_var2 of var1 is 4, and var 2 = Bye>
感谢您的帮助,将其推送到可以穿越我的脑海的地方!
Grateful for any help, push to a site that will get through the brick wall of my mind!!
推荐答案
执行 print(t.change_var1)
时,您不是调用 change_var1功能
,您只是引用.它没有被调用,因此实际上没有任何作用.
When you do print(t.change_var1)
, you are not calling the change_var1 function
, you are merely referencing it. It is not getting called, so it doesn't actually do anything.
要调用它,您需要添加括号:
To call it you need to append parentheses:
print(t.change_var1())
print(t.change_var2())
这篇关于Python更改__init__中声明的变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!