python Class内置方法解析

class People(object):
    """注解:人类"""

    # 初始化函数
    def __init__(self, name):
        self.name = name

    # 析构函数,一般解释器会自动分配和释放内存,
    # 所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。
    def __del__(self):
        pass

    # print输出对象调用 print(people)
    def __str__(self):
        return "str函数被调用"

    # 直接使用对象时调用 people
    def __repr__(self):
        return "repr函数被调用"

    # 对象当做方法时调用,例people()
    def __call__(self, *args, **kwargs):
        print("call函数被调用")

    # 用于索引操作,可如字典般使用
    # 获取对象属性,people['name']
    def __getitem__(self, item):
        return getattr(self, item)

    # 设置对象属性,people['name'] = 'Jack'
    def __setitem__(self, key, value):
        setattr(self, key, value)

    # 删除对象属性,del people['name']
    def __delitem__(self, key):
        delattr(self, key)

    # 正常情况下,当我们调用类的方法或属性时,如果不存在,就会报错
    # 当对未定义的属性名称和实例进行点号运算时,就会用属性名作为字符串调用这个方法
    def __getattr__(self, item):
        if item == 'age':
            return 18

    # 会拦截所有属性的的赋值语句。如果定义了这个方法,self.arrt = value 就会变成self,__setattr__("attr", value)
    # 当在__setattr__方法内对属性进行赋值是,不可使用self.attr = value,因为他会再次调用self,__setattr__("attr", value),则会形成无穷递归循环,最后导致堆栈溢出异常
    # 应该通过对属性字典做索引运算来赋值任何实例属性,也就是使用self.__dict__['name'] = value
    def __setattr__(self, key, value):
        super().__setattr__(key, value)

    def __delattr__(self, key):
        super().__delattr__(key)


people = People('Jack')

print(people.__doc__)  # 注解:人类
print(People.__doc__)   # 注解:人类

print(people.__module__)    # __main__
print(People.__module__)    # __main__

print(people.__class__)  # 
print(People.__class__)  # 

print(people.__dict__)  # {}
# {'__module__': '__main__', '__doc__': '注解:人类',
# '__init__': ,
# '__del__': ,
# '__str__': ,
# '__repr__': ,
# '__call__': ,
# '__getitem__': ,
# '__setitem__': ,
# '__delitem__': ,
# '__getattr__': ,
# '__setattr__': ,
# '__delattr__': ,
# '__dict__': ,
# '__weakref__': }
print(People.__dict__)

print(People)  # 
print(people)  # str函数被调用
people  # 啥也输出,不知道为啥
people()  # call函数被调用

print(people['name'])  # Jack
people['name'] = 'Tom'
print(people['name'])   # Tom
del people['name']
print(people['name'])   # None

print(people.age)   # 18

你可能感兴趣的:(python Class内置方法解析)