(1)私有属性
class MyClass: attr1 = 'attr1' # 共有属性 _attr2 = '_attr2' # 私有属性,可直接访问 __attr3 = '__attr3' # 私有属性,改变了属性名:_MyClass__attr3 m1 = MyClass() print(m1.attr1) print(MyClass.attr1) print(m1._attr2) print(MyClass._attr2) print(m1._MyClass__attr3) print(MyClass._MyClass__attr3) print(MyClass.__dict__) m1.att = 'gaga' # 可动态添加属性
输出:
attr1
attr1
_attr2
_attr2
__attr3
__attr3
{'__module__': '__main__', 'attr1': 'attr1', '_attr2': '_attr2', '_MyClass__attr3': '__attr3', '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}
(2)__slots__ 和 __dict__
class MyClass2: __slots__ = ['name'] m2 = MyClass2() m2.name = 'haha' # m2.cc = 'hh' # AttributeError: 'MyClass2' object has no attribute 'cc';只能添加slots里面声明的属性 print(m2.name) print(MyClass2.__dict__)
输出:
haha
{'__module__': '__main__', '__slots__': ['name'], 'name': <member 'name' of 'MyClass2' objects>, '__doc__': None}