為什么這會列印“所以它必須是:測驗測驗”而不是“所以它必須是:你好是我”
class bob():
subjectTemp='test'
levelTemp='test'
def setSubject(function_subject):
bob.subjectTemp=function_subject
print(bob.subjectTemp)
def setLevel(function_level):
bob.levelTemp=function_level
print(bob.levelTemp)
def join(subject=subjectTemp, level=levelTemp):
print("So it must be:", subject, level)
bob.setSubject("hello")
bob.setLevel("it's me")
bob.join()
uj5u.com熱心網友回復:
直接的“問題”是 this 在函式定義時系結:
def join(subject=subjectTemp, level=levelTemp):
的值subject將是subjectTemp函式宣告時的值,并且不會改變。有關詳細資訊,請參閱“Least Astonishment”和可變默認引數。
更大的問題是這根本不是你使用類的方式。你想要這樣的東西:
class Bob():
subject = 'test'
level = 'test'
def set_subject(self, subject):
self.subject = subject
print(self.subject)
def set_level(self, level):
self.level = level
print(self.level)
def join(self):
print("So it must be:", self.subject, self.level)
b = Bob()
b.set_subject("hello")
b.set_level("it's me")
b.join()
uj5u.com熱心網友回復:
subjectTemp 和 levelTemp 具有默認值。
你可以寫:
class bob():
subjectTemp='test'
levelTemp='test'
def setSubject(function_subject):
bob.subjectTemp=function_subject
print(bob.subjectTemp)
def setLevel(function_level):
bob.levelTemp=function_level
print(bob.levelTemp)
def join():
print("So it must be:", bob.subjectTemp, bob.levelTemp)
bob.setSubject("hello")
bob.setLevel("it's me")
bob.join()
uj5u.com熱心網友回復:
默認值在函式定義時評估一次。這是新 Python 愛好者在使用諸如串列之類的可變引數時偶然發現的一個經典問題——但這是相同陷阱的另一個實體。
您可以在官方檔案中閱讀有關默認引數的更多資訊。
特別是:“重要警告:默認值僅評估一次”。
編輯:這是您所問問題的技術解釋,但請在此處閱讀其他人的評論和答案。這是使用 Python 類的一種特殊方式,它可能會讓你在路上絆倒。請谷歌“Pythonic 代碼”和“慣用代碼”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/452153.html
標籤:Python python-3.x 功能 班级 变量
