getattr() 函数用于返回一个对象属性值。
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
getattr()语法结构:
getattr(object, name[, default])
返回值:返回对象属性值。
示例代码1:
class Test(object):
x = 1
a = Test()
print(getattr(a, 'x')) # 获取属性 x 值
print(getattr(a, 'y', 'None')) # 获取属性 y 值不存在,但设置了默认值
# print(getattr(a, 'y')) # AttributeError: 'Test' object has no attribute 'y'
print(a.x) # 效果等同于上面
运行结果:
示例代码2:
class Demo(object):
def __init__(self):
self.name = '张三'
self.age = '25'
def first(self):
print("这是 first 方法")
return "one"
def second(self):
print("这是 second 方法")
a = Demo()
# 如果a对象中有属性name则打印self.name的值,否则打印'non-existent'
print(getattr(a, 'name', 'non-existent'))
print("*" * 100)
# 如果a对象中有属性age则打印self.age的值,否则打印'non-existent'
print(getattr(a, 'age', 'non-existent'))
print("*" * 100)
# 如果有方法first,打印其地址,否则打印default
print(getattr(a, 'first', 'default'))
print("*" * 100)
# 如果有方法first,运行函数并打印返回值,否则,打印default
print(getattr(a, 'first', 'default')())
print("*" * 100)
# 如果有方法second,运行函数并打印None否则打印default
print(getattr(a, 'second', 'default')())
运行结果:
示例代码3: 【对对象中的方法传参使用】
class Demo(object):
def run(self, name, age):
return f"My name is {name}, age is {age}!"
aa = getattr(Demo, 'run')
print(aa)
bb = getattr(Demo(), 'run')
print(bb)
cc = getattr(Demo, 'run')(1, "dgw", "26")
print(cc)
dd = getattr(Demo(), 'run')("dgw", "26")
print(dd)
运行结果:
示例代码4: 【requests方法使用getattr()】
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
# 最后有没有问号结果都一样
url = 'https://www.baidu.com/s?'
# 请求参数是一个字典 即wd=python
kw = {'wd': 'python'}
# 方法一:
# 带上请求参数发起请求,获取响应
response = requests.get(url, headers=headers, params=kw)
print(response.status_code)
print(response.url)
# 方法二:使用getattr()
response2 = getattr(requests, 'get')(url, headers=headers, params=kw)
print(response2.status_code)
print(response2.url)
运行结果: