我是 python 新手,并嘗試在類中為我的 bool 獲取新值。
我嘗試創建一個全域的,在 init 中設定。
如何在 getnewvalue() 中獲取測驗布林值的新值?
這是我的代碼:
test = False
class myclass():
def changevalue()
test = True
getnewvalue()
def getnewvalue():
print(test)
uj5u.com熱心網友回復:
如果你想在你的類中保存資料,那么使用__init__()
并保存它是個好主意。Python 教程中的更多內容:類物件。
并使用__init__用所需的值初始化類。您的代碼應如下所示:
test = False
class myclass():
def __init__(self, test):
self.test = test # self keyword is used to access/set attrs of the class
# __init__() gets called when the object is created, if you want to call
# any function on the creation of the object after setting the values
# you can do it here
self.changevalue()
def changevalue(self): # if you want to access the values of the class you
# need to pass self as a argument to the function
self.test = not test
self.getnewvalue()
def getnewvalue(self):
print(self.test) # use self to access objects test value
_class = myclass(False)
或者,如果您只想擁有一個帶有函式的類,您可以執行以下操作:
test = False
class myclass():
@staticmethod
def changevalue(val)
return not val
@staticmethod
def getnewvalue():
print(test)
_class = myclass()
test = _class.changevalue(test)
這樣它就不會在呼叫時列印您的值,因為它只是將您的值設定為回傳該函式。你必須自己做,但這不應該是一個問題。更多關于靜態方法的資訊:@staticmethod
uj5u.com熱心網友回復:
添加
global test
到這兩個功能。生成的代碼將是...
test = False
class myclass():
def changevalue():
global test
test = True
getnewvalue()
def getnewvalue():
global test
print(test)
global允許函式訪問自身外部的變數。希望這可以幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474363.html
上一篇:四個非零非負值
