类与对象的变量查找顺序

__dict__: 查看对象的实例化属性列表

python首先会去实例化对象属性列表去寻找,如果找不到,不会直接返回None,会继续去类中查找,这也是为什么s1的实例化对象属性列表为{},却依然能打印出scott的原因

class Student(object):
    name = "scott"
    age = 0
    def __init__(self,name,age):
        name = name
        age = age

s1 = Student("张三",1)       
print(s1.name) # scott
print(s1.__dict__) # {}
print(Student.name)  # scott
class Student(object):
    name = "scott"
    age = 0
    def __init__(this,name,age):
        this.name = name
        this.age = age

s1 = Student("张三",1)       
print(s1.name) # 张三
print(s1.__dict__) # {'name': '张三', 'age': 1}
print(Student.name)  #scott

当然你也可以打印类的属性列表:

print(Student.__dict__)
{'__module__': '__main__', 'name': 'scott', 'age': 0, '__init__': <function Student.__init__ at 0x7f9aa5a57550>, '__dict__': <attribute '__dict__' of 'Student' objects>, '__weakref__': <attribute '__weakref__' of 'Student' objects>, '__doc__': None}

总结

先去实例化对象属性列表中查找 => 本类中查找 => 父类中查找

思考

  1. 这里的name,age打印的是什么?
class Student(object):
    name = "scott"
    age = 0
    def __init__(this,name,age):
        this.name = name
        this.age = age
        print(name)
        print(age)

s1 = Student("张三",1)
张三
1
  1. 如何操作类变量? 怎么修改sum?
class Student(object):
    sum = 0
    def __init__(this,name,age):
        this.name = name
        this.age = age

results matching ""

    No results matching ""