广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python中getattr()函数用法详解
  • 887
分享到

python中getattr()函数用法详解

pythonattr 2023-09-08 21:09:08 887人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

getattr() 函数用于返回一个对象属性值。 def getattr(object, name, default=None): # known special case of getattr """ getattr(obje

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])
  • object -- 对象。
  • name -- 字符串,对象属性。
  • default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

返回值:返回对象属性值。

示例代码1:

class Test(object):    x = 1a = 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,打印其地址,否则打印defaultprint(getattr(a, 'first', 'default'))print("*" * 100)# 如果有方法first,运行函数并打印返回值,否则,打印defaultprint(getattr(a, 'first', 'default')())print("*" * 100)# 如果有方法second,运行函数并打印None否则打印defaultprint(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 requestsheaders = {    "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=pythonkw = {'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)

运行结果:

来源地址:https://blog.csdn.net/weixin_44799217/article/details/125941122

--结束END--

本文标题: python中getattr()函数用法详解

本文链接: https://www.lsjlt.com/news/400604.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作