Justin-刘清政的博客

python/面向对象基础/6-对象属性查找顺序

2020-12-21

一、属性查找

  • 先从对象自己的名称空间找,没有则去类中找,如果类也没有则报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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')
1
print(OldboyStudent.count)
1
0
1
2
stu1 = OldboyStudent('nick', 18, 'male')
print(stu1.count)
1
1
1
2
stu2 = OldboyStudent('sean', 17, 'male')
print(stu2.count)
1
2
1
2
stu3 = OldboyStudent('tank', 19, 'female')
print(stu3.count)
1
3
1
print(OldboyStudent.count)
1
3
1
print(stu1.name)
1
nick
  • 由于上述修改的是类属性,类属性的count已经被修改为3,所以其他实例的count都为3
1
print(stu1.count)
1
3
1
print(stu2.count)
1
3
1
print(stu3.count)
1
3
  • 由于aa是私有属性,因此stu们都会用自己私有的aa,不会用类的aa
1
print(stu1.__dict__)
1
{'name': 'nick', 'age': 18, 'sex': 'male', 'aa': 1}
1
print(stu2.__dict__)
1
{'name': 'sean', 'age': 17, 'sex': 'male', 'aa': 1}
1
print(stu3.__dict__)
1
{'name': 'tank', 'age': 19, 'sex': 'female', 'aa': 1}
使用支付宝打赏
使用微信打赏

点击上方按钮,请我喝杯咖啡!

扫描二维码,分享此文章