class Student:
def __init__(self,m1,m2):
m1=m1
m2=m2
print(m1 m2)
s1=Student(10,20)
s2=Student(20,30)
print(Student.m1)
#i 剛剛開始 oops 概念,所以現在有點困惑。撰寫“print(Student.m1) 或 print(s1.m1)”時出現編譯時錯誤,因為“AttributeError: type object 'Student' has no attribute 'm1'”。
uj5u.com熱心網友回復:
如果不使用self,則只是將值分配給函式完成后無法訪問的區域變數。
如果使用self.m1,則將值分配給 self 的屬性,以后可以訪問。
uj5u.com熱心網友回復:
如果您不將值設定為屬性(通過self),則名稱(m1,m2..)在超出范圍時(__init__(...)回傳時)會丟失
這實際上與在函式中使用名稱相同 - 它們只存在于該范圍內,除非放在其他地方!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494852.html
