欢迎来到Cecilia陈的博客

孤独,是人一生最好的修行。

079 类的属性查找

类的属性查找

  • 先从对象自己的名称空间找,没有则取类里找,如果类里也没有则程序报错
class Student1:
    # 定义类的相同属性
    school = 'xiwangzhongxue'
    count = 0
    aaa = 10

    # 定义类的相同方法
    # 定义类的属性方法
    def __init__(self,name,age):
        self.name = name
        self.age = age
        
        Student.count += 1
        self.aaa = 1

    def choice(self):
        print('选课...')

    def study(self):
        print('学习....')
print(Student.count)

0

stu1 = Student('小明',18)
print(stu1.count)

1

stu2 = Student('小红',20)
print(stu2.count)

2

print(Student.count)

2

print(stu1.name)

小明

  • 由于count += 1时修改的类的属性,类的属性count已经被修改为2,所以其他实例对象的count属性都为2
print(stu1.count)
print(stu2.count)

2

2

  • 由于aaa是每个实例的私有属性,因此所有的实例对象都会用自己私有的aaa,不会用类的aaa
print(stu1.__dict__)

{'name': '小明', 'age': 18, 'aaa': 1}

print(stu2.__dict__)

{'name': '小红', 'age': 20, 'aaa': 1}

posted @ 2019-08-26 20:29  Cecilia陈  阅读(113)  评论(0编辑  收藏  举报