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)

0python

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

1学习

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

2code

print(Student.count)

2对象

print(stu1.name)

小明it

  • 因为count += 1时修改的类的属性,类的属性count已经被修改成2,因此其余实例对象的count属性都为2
print(stu1.count)
print(stu2.count)

2class

2程序

  • 因为aaa是每一个实例的私有属性,所以全部的实例对象都会用本身私有的aaa,不会用类的aaa
print(stu1.__dict__)

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

print(stu2.__dict__)

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

相关文章
相关标签/搜索