私有属性:
类里面定义的变量叫类属性,分为公有属性和私有属性
私有属性定义:
单下划开头;_attr 在外部可以直接访问
双下划线开头:__attr1 在外部不能直接访问,被改名,所有在外部无法访问(_类名__attr1)
__dict__
类调用__dict__ 属性,返回类属性和方法的字典
实例调用__dict__ 属性,返回值实现的相关的实例属性
__slots__:限制对象可以设置的属性
class MyTest: attr = 100 __slots__ = ['name', 'age'] m = MyTest() m.name = 'aa' m.age = 19 print(m.name)
__getattribute__:查找属性触发的方法
__getattr__: __getattribute__没有找的属性会触发这个方法
__setattr__:设置属性触发的方法
__delattr__:删除属性触发的方法
class Test(object): name=199 def __setattr__(self, key, value): print('设置属性,会调用此方法') super().__setattr__(key,value) def __getattr__(self, item): print('没有找到属性时,触发AttributeError异常时会调用此方法') def __getattribute__(self, item): print('查找属性时,首先会进入该方法中') return super().__getattribute__(item) def __delattr__(self, item): print('属性被删除了') super().__delattr__(item) c=Test() print(c.name) c.age=19 print(c.age) print(c.ss)