目录
属性查找
- 先从对象自己的名称空间找,没有则去类中找,如果类也没有则报错
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}