优酷项目遇到的知识点回顾

'''
hasattr(object,name)

判断一个对象里面是否有name属性或者name方法,返回bool值,有name特性返回True,否则返回False
需要注意name要用引号包起来
'''

class test():
    name = 'michael'
    def run(self):
        return 'hello python'
t = test()
t1 = hasattr(t,'name')
t2 = hasattr(t,'age')
print(t1,t2)      #True False


'''
getattr(object,name[,default])
获取对象object的属性或者方法,存在就返回出来,不存在就返回出默认值,默认值可选
需要注意,如果name是对象的方法,返回值是该方法的内存地址,想运行该方法,要加上()
name是属性,直接返回该值,这里的name同样需要引号!
'''
class test1():
    name = 'michael'
    def run(self):
        return 'big house'
t = test1()
t1 = getattr(t,'name')
print(t1)    #michael
t2 = getattr(t,'age','不存在这个值,输出我哦!')
print(t2)    #不存在这个值,输出我哦!
t3 = getattr(t,'run')
print(t3)    #<bound method test1.run of <__main__.test1 object at 0x00000000021B8D68>>


'''
setattr(object,name,values)
给对象的属性赋值,若不存在,先创建后赋值,没有返回值!!!
'''

class test2():
    name = 'michael'
    def run(self):
        return 'beautiful girl!'
t = test2()
print(hasattr(t,'age'))  #False
setattr(t,'age','24')
print(hasattr(t,'age'))  #True
print(t.age)             #24

print('----------------------------------')

# python的__getatrr__和__setattr__方法

'''
__getattr__:
拦截点号运算。对象 .属性: 如果找不到属性,就用属性名作为字符串,调用该方法:
如果继承树可以找到该属性,则不会调用该方法
'''
class text3:
    def __getattr__(self, item):
        if item == 'age':
            return 24
        else:
            raise AttributeError
x = text3()
print(x.age)  #24
# print(x.name)  #自定义报错


print('-------------------------')

'''
__setattr__:
拦截所有属性的赋值语句。定义了该方法,self.name=value 就会变成 self.__setattr__('name',value)
需要注意:当在__steattr__方法内对属性进行赋值时,不可使用self.name=value,否则会出现无限递归循环。
应该对属性字典做索引运算来赋值任何实例属性,也就是self.__dict__['name'] = value
'''
class text4():
    def __init__(self,age1,name):
        self.age = age1
        self.name =name
    def f(self):
        print(self.__dict__)
    def __getattr__(self, item):
        print('__getattr__')
    def __setattr__(self, key, value):
        print('__setattr__')
        self.__dict__[key]=value
x = text4(24,'michael')  #__init__方法内部存在两个赋值语句,因此调用两次__setattr__
x.f()  #{'age': 24, 'name': 'michael'}
print('_____')
x.a          #不存在属性a,因此走__getattr__方法
x.a=333      #即使该属性不存在,只要赋值了,就激发__setattr__方法,给对象添加了一个新的属性
x.f()  #{'age': 24, 'name': 'michael', 'a': 333}

  

原文地址:https://www.cnblogs.com/changwenjun-666/p/10899888.html