美文网首页
在当前类查找某个属性 getattr 效率对比字典 2018-0

在当前类查找某个属性 getattr 效率对比字典 2018-0

作者: 夏树的宝马 | 来源:发表于2018-09-29 10:55 被阅读11次

通过测试对比 在当前类实例中查找某个属性
1.使用object.dict.get()与getattr():
1.1.查找存在的属性时,这两种方法效率相差不大
1.2.当查找不存在的属性时,发现object.dict.get()这种方式要快些

import random
class test_getattr():
    def __init__(self):
        self.num=0

    def set_random_prop(self,times=1000):
        for x in  range(times):
            random_name=''.join(random.choice('qwertyuisdfghjkxcvbnmbn') for i in range(times))
            setattr(self,random_name,random_name)

    def get_prop_time(self,prop=None,times=100):
        start=time.time()
        while times>0:

            getattr(self,prop,False)
            # self.__dict__.get(prop)
            times -=1
        print(time.time()-start)

mytest=test_getattr()
mytest.set_random_prop()
mytest.get_prop_time(prop='sadf',times=10000000)

如图:

getattr查找存在的属性 object.__dict__.get()查找存在的属性 getattr查找不存在的属性 object.__dict__.get()查找不存在的属性

相关文章

网友评论

      本文标题:在当前类查找某个属性 getattr 效率对比字典 2018-0

      本文链接:https://www.haomeiwen.com/subject/vkevoftx.html