对象属性查找顺序

对象属性查找顺序

一、属性查找

  • 先从对象自己的名称空间找,没有则去类中找,如果类也没有则报错
class Student:
    school = 'oldboy'
    count = 0
    num = 10

    def __init__(self, x, y, z):
        self.name = x
        self.age = y
        self.sex = z

        Student.count += 1

        self.num = 1

    def choose_course(self):
        print('is choosing course')
print(Student.count)

0

stu1 = Student('laowang', 18, 'male')
print(stu1.count)

1

stu2 = Student('xulou', 17, 'male')
print(stu2.count)

2

stu3 = Student('laoliu', 19, 'male')
print(stu3.count)

3

print(stu1.name)

laowang

# 由于上述修改的是类属性,类属性的count已经被修改为3,所以其他实例的count都为3

print(stu1.count)
print(stu2.count)
print(stu3.count)

3
3
3

# 由于num是私有属性,因此stu们都会用自己私有的num,不会用类的num
print(stu1.num)
print(stu2.num)
print(stu3.num)

1
1
1

print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)

{'name': 'laowang', 'age': 18, 'sex': 'male', 'num': 1}
{'name': 'xulou', 'age': 17, 'sex': 'male', 'num': 1}

posted @ 2019-08-26 19:40  RandySun  阅读(389)  评论(0编辑  收藏  举报