下面的代碼是更大代碼的簡化版本。我要執行的主要操作是使用和更改rank函式progress內部inc_progress(self)。
class User:
rank=-8
progress=0
def inc_progress(self):
global rank, progress
rank =1
print(rank,progress)
u=User()
u.inc_progress()
但它給了我錯誤:NameError: name 'rank' is not defined. Did you mean: 'range'?
有誰知道這個問題的可能解決方法,以便我可以使用和更改rank函式中progress的值inc_progress(self)
uj5u.com熱心網友回復:
通過定義rank和progress之外__init__,您已將它們定義為類變數,這意味著它們屬于該類并且可用于該類的所有實體。https://pynative.com/python-class-variables/
這是您的代碼的修改版本,它可以滿足您的期望(可能還有一些您沒有做的事情!)
class User:
rank=-8
progress=0
def inc_progress(self):
User.rank =1
print(User.rank, User.progress)
u=User()
u.inc_progress() # Output: -7, 0
好,很好!問題解決了,對吧?也許。看這個。
u=User()
u.inc_progress() # Output: -7, 0
u2 = User()
print(u2.rank, u2.progress) # Output: -7, 0
等等,什么?新創建的實體的Userrank=-7 而不是 -8!那是你的類變數。如果您想要rank并且progress特定于實體,請在初始化期間定義它們并像往常一樣訪問它們self
class User:
def __init__(self):
self.rank=-8
self.progress=0
def inc_progress(self):
self.rank =1
print(self.rank, self.progress)
u=User()
u.inc_progress() # Output: -7, 0
u2 = User()
print(u2.rank, u2.progress) # Output: -8, 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521505.html
