一、__dict__函数
__dict__函数是用来存储对象属性的一个字典,其键为属性名,值为属性的值。许多内建类型就没有__dict__属性,如list,此时就需要用dir()来列出对象的所有属性。
class Apple(object): 'fruit' color = 'red' def __init__(self): self.weight = '300' self.smell = 'good' @property def price(self): return self.weight*10 def taste(self): pass MyApple = Apple()
print Apple.__dict__ { 'taste': <function taste at 0x038C9E30>, #类方法,所在地址为0x038C9E30 '__module__': '__main__', #所处模块 '__dict__': <attribute '__dict__' of 'Apple' objects>, #暂不深究 'color': 'red', #类变量 'price': <property object at 0x038CD330>, #特性对象 '__weakref__': <attribute '__weakref__' of 'Apple' objects>, #弱引用 '__doc__': 'fruit', #说明 '__init__': <function __init__ at 0x038C9DB0> #类方法 }
print MyApple.__dict__ {'smell': 'good', 'weight': '300'} #只有实例的两个属性由上实验可知,
1、实例的__dict__仅存储与该实例相关的实例属性,正是因为实例的__dict__属性,每个实例的实例属性才会互不影响。
2、类的__dict__存储所有实例共享的变量和函数(类属性,方法等),但类的__dict__并不包含其父类的属性。
二、dir( )函数
dir() 是 Python 提供的一个 API 函数,会自动寻找一个对象的所有属性。从第一节可知,一个实例对象的__dict__里只有实例属性,没有包含其他的有效属性。因此如果想获取一个对象所有有效属性,可以使用dir()。
class Apple(object): 'fruit' color = 'red' def __init__(self): self.weight = '300' self.smell = 'good' @property def price(self): return self.weight*10 def taste(self): pass MyApple = Apple()
print dir(Apple) print dir(MyApple) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'price', 'taste'] ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'color', 'price', 'smell', 'taste', 'weight']由上实验可知,dir( )在对象中自动搜索到了 包括从父类中继承的所有属性(如:__new__)。
三、__slots__( )函数
如果类没有定义__slots__ ,该类的实例会有__dict__属性,通过__dict__可修改,删除,增加实例属性。首先定义一个类
class Apple(object): pass
然后创建一个实例,并给实例添加属性和方法。
MyApple=Apple() print MyApple.__dict__ #{} MyApple.weight=300 #动态语言的灵活性 print MyApple.__dict__ #{'weight': 300} price=lambda x: x*10 MyApple.price=price print MyApple.__dict__ #{'price': <function <lambda> at 0x03987C30>, 'weight': 300}
在一个类中定义了__slots__属性,那么这个类的实例将不能添加实例属性,也不会拥有__dict__属性。__slots__的作用就是阻止类在实例化时为实例分配__dict__属性和 __weakref__,从而限制实例属性的添加,因此可以节约内存。
class Apple(object): __slots__ = ('weight','price') MyApple=Apple() MyApple.weight=300 MyApple.price=10 MyApple.smell='good' Traceback (most recent call last): File "e:\Job\TSC\CodeCloud\cxDBTest.py", line 203, in <module> MyApple.smell='good' AttributeError: 'Apple' object has no attribute 'smell'
参考资料:https://blog.csdn.net/lis_12/article/details/53521554
https://blog.csdn.net/lis_12/article/details/53511300
扫描二维码关注公众号,回复:
540630 查看本文章