Python

Python的attr三兄弟(getattr、hasattr、s

2019-02-15  本文已影响0人  Donald_32e5
wallhaven-408866.png

阅读源码的时候,经常看见hasattrgetattrsetattr,感觉很酷炫的同时,也是不解其义,特此来说说道说道这三兄弟

getattr已经介绍过了,主要说说setattr和hasattr

hasattr(对象,属性名) wallhaven-408866.png

I、基本操作
class Test:
   @property
   def name(self):
       return "Despair"

   @property
   def age(self):
       return 11


T = Test()
print(hasattr(T, 'name'))
print(getattr(T, 'name', None))
print(hasattr(T, 'age'))
print(getattr(T, 'age', None))
-----
True
Despair
True
11
II、速度效益
from timeit import timeit


description = '''\
class Test:
    @property
    def name(self):
        return 'Donald'
a = Test()
'''

stm = '''\
hasattr(a,'name')
'''
print(f'hasattr 执行10000次所需时间:{timeit(stmt=stm, setup=description, number=10000)}')

stm = '''\
getattr(a, 'name', None)
'''
print(f'getattr 执行10000次所需时间:{timeit(stmt=stm, setup=description, number=10000)}')

-----
hasattr 执行10000次所需时间:0.0015951709999999994
getattr 执行10000次所需时间:0.0016753230000000029

setattr(对象,key, value)

I、基础操作
class Test:
      def __init__(self):
            self.name = "Donald"

      def name(self):
           return self.name  

a = Test()
print(a.__dict__)
setattr(a, 'a', 'hello')               # setattr()
print(a.__dict__)
a.__setattr__('b', 'world')           #__setattr__()
print(a.__dict__)

*****
# 第三方模块
import requests
b = requests.session()     # request的一个方法
print(b.__dict__)
b.__setattr__('a', 'hello')
print(b.__dict__)
------
# 新加的在最后面
{'headers': {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'auth': None, 'proxies': {}, 'hooks': {'response': []}, 'params': {}, 'stream': False, 'verify': True, 'cert': None, 'max_redirects': 30, 'trust_env': True, 'cookies': <RequestsCookieJar[]>, 'adapters': OrderedDict([('https://', <requests.adapters.HTTPAdapter object at 0x120b6f0b8>), ('http://', <requests.adapters.HTTPAdapter object at 0x1212b3ef0>)])}
{'headers': {'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'auth': None, 'proxies': {}, 'hooks': {'response': []}, 'params': {}, 'stream': False, 'verify': True, 'cert': None, 'max_redirects': 30, 'trust_env': True, 'cookies': <RequestsCookieJar[]>, 'adapters': OrderedDict([('https://', <requests.adapters.HTTPAdapter object at 0x120b6f0b8>), ('http://', <requests.adapters.HTTPAdapter object at 0x1212b3ef0>)]), 'a': 'hello'}


*****
# 数据类型
a = set()
print(a.__dict__)
------
AttributeError: 'set' object has no attribute '__dict__'

II、魔法方法
class Test:
    """测试类"""

    @staticmethod
    def name():
        return "Donald"

    def __setattr__(self, key, value):
        print(f'key->{key}')
        self.key = value


a = Test()
a.age = 10
-------------
key->key
  ·   # 很多个
  ·
key->key
RecursionError: maximum recursion depth exceeded while calling a Python object
class Test:
    """测试类"""

    @staticmethod
    def name():
        return "Donald"

    def __setattr__(self, key, value):
        print(f'key->{key}')
        self.__dict__[key] = value


a = Test()
a.age = 10
print(a.__dir__())
-----
key->age
['age', '__module__', '__doc__', 'name', '__setattr__', '__dict__', '__weakref__', '__repr__', '__hash__', '__str__', '__getattribute__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']

综上所所述:getattr在日常开发中用到的最多,当属老大,hasattr紧随其后,setattr的地位感觉会被property冲击

上一篇 下一篇

猜你喜欢

热点阅读