python中的 __getattr__ __setattr__ __getitem__ __add__

class Foo():

    def __str__(self):

        return "好好学习"

    def __getattr__(self, item):
        return "0000"

    def __setattr__(self, key, value):
        self.__dict__[key]=value

    def __getitem__(self, item):
        return 11111

    def __add__(self, other):
        return other + 1


obj = Foo()
print(obj)  #调用__Str__          #打印结果:好好学习
print(obj.x) #调用 __getattr__    #打印结果:0000

#当使用赋值语句对属性进行设置时,python会自动调用__setattr__()方法,
# 如果该属性不存在,则会调用__setattr__()对实例属性赋值,被赋值的属性和值会存入实例属性字典__dict__中
obj.x0=222 #设置属性
print(obj.x0) #打印结果:222

print(obj['x1']) #调用 __getitem__  #打印结果:11111

print(obj+8)    #调用 __add__  #打印结果:9

 

posted @ 2018-11-09 10:56  CHVV  阅读(336)  评论(0编辑  收藏  举报