079 类的属性查找

Posted xichenhome

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于079 类的属性查找的主要内容,如果未能解决你的问题,请参考以下文章

为啥不在实例属性查找中搜索元类的属性?

类的属性查找

每个类的jquery单击事件以查找href属性

python-属性的查找与绑定方法

python:属性查找与绑定方法

属性查找;绑定到对象的方法的特殊之处;对象之间的交互