hasattr
、getattr
、setattr
,感觉很酷炫的同时,也是不解其义,特此来说说道说道这三兄弟getattr已经介绍过了,主要说说setattr和hasattr
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
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)
等效于setattr()。但是对自带的几种基本数据类型不起作用···具体原因,我目前不清楚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': , 'adapters': OrderedDict([('https://', ), ('http://', )])}
{'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': , 'adapters': OrderedDict([('https://', ), ('http://', )]), 'a': 'hello'}
*****
# 数据类型
a = set()
print(a.__dict__)
------
AttributeError: 'set' object has no attribute '__dict__'
__setattr__
方法之后,添加一个新的属性的时候,会调用这个方法__setattr__
方法的时候,他传入的值不能直接使用,否则会陷入无限递归中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
self.__dict__[key] = value
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__']