對象屬性查找順序

目錄python

1、屬性查找

  • 先從對象本身的名稱空間找,沒有則去類中找,若是類也沒有則報錯
class OldboyStudent:
    school = 'oldboy'
    count = 0
    aa = 10

    def __init__(self, x, y, z):  #會在調用類時自動觸發
        self.name = x  # stu1.name='耗哥'
        self.age = y  # stu1.age=18
        self.sex = z  # stu1.sex='male'
        OldboyStudent.count += 1
        #         self.count += 5
        self.aa = 1

    def choose_course(self):
        print('is choosing course')
print(OldboyStudent.count)
0
stu1 = OldboyStudent('nick', 18, 'male')
print(stu1.count)
1
stu2 = OldboyStudent('sean', 17, 'male')
print(stu2.count)
2
stu3 = OldboyStudent('tank', 19, 'female')
print(stu3.count)
3
print(OldboyStudent.count)
3
print(stu1.name)
nick
  • 因爲上述修改的是類屬性,類屬性的count已經被修改成3,因此其餘實例的count都爲3
print(stu1.count)
3
print(stu2.count)
3
print(stu3.count)
3
  • 因爲aa是私有屬性,所以stu們都會用本身私有的aa,不會用類的aa
print(stu1.__dict__)
{'name': 'nick', 'age': 18, 'sex': 'male', 'aa': 1}
print(stu2.__dict__)
{'name': 'sean', 'age': 17, 'sex': 'male', 'aa': 1}
print(stu3.__dict__)
{'name': 'tank', 'age': 19, 'sex': 'female', 'aa': 1}
相關文章
相關標籤/搜索