当前位置: 首页 > 编程笔记 >

Python通过getattr函数获取对象的属性值

皇甫伟彦
2023-03-14
本文向大家介绍Python通过getattr函数获取对象的属性值,包括了Python通过getattr函数获取对象的属性值的使用技巧和注意事项,需要的朋友参考一下

英文文档:

getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

  获取对象的属性值

说明:  

  1. 函数功能是从对象object中获取名称为name的属性,等效与调用object.name。

#定义类Student
>>> class Student:
  def __init__(self,name):
    self.name = name

    
>>> s = Stduent('Aim')
>>> getattr(s,'name') #等效于调用s.name
'Aim'
>>> s.name
'Aim'

  2. 函数第三个参数default为可选参数,如果object中含义name属性,则返回name属性的值,如果没有name属性,则返回default值,如果default未传入值,则报错。

#定义类Student
>>> class Student:
  def __init__(self,name):
    self.name = name

>>> getattr(s,'name') #存在属性name
'Aim'

>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值
6

>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
 File "<pyshell#17>", line 1, in <module>
  getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'

与__getattr__的区别:

__getattr__是类的内置方法,当找不到某个属性时会调用该方法;找到就不会调用.

getattr与类无关.

一个例子:作为data的代理类,可以以这种方式来使用data的属性.

class DataProxy(...):
  def __getattr__(self, item):
    return getattr(self.data, item)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 4.4. 通过 getattr 获取对象引用 4.4.1. 用于模块的 getattr 4.4.2. getattr 作为一个分发者 你已经知道 Python 函数是对象。 你不知道的是,使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 例 4.10. getattr 介绍 >>> li = ["Larry", "Curly"] >>> li.pop

  • 本文向大家介绍在Python中通过getattr获取对象引用的方法,包括了在Python中通过getattr获取对象引用的方法的使用技巧和注意事项,需要的朋友参考一下 getattr函数 (1)使用 getattr 函数,可以得到一个直到运行时才知道名称的函数的引用。 (2)用于模块的 getattr : getattr不仅仅适用于内置数据类型,也可作用于模块。 (3)getattr 作为一 个分

  • 在 PowerShell 中,如何通过指定对象的名称(字符串)来获取对象的属性值?我想要类似这样的东西: 是否有类似于“获取属性名称”的内容?

  • 问题内容: 这个问题很简单,但是由于我是python的新手,所以我从php过来了,因此遇到了一些错误。 我有以下简单的课程: 在PHP中,我可以执行以下操作: 我该如何在python中做到这一点? 问题答案: 要访问对象的字段或方法,请使用dot : 如果将在运行时定义字段名称,请使用内置函数:

  • 使用此答案中的代码:获取Tkinter上的顶级级别列表: 我这样称呼它: 输出如下: 它正确地显示了两个顶级。首先是一个音乐图书馆的树状视图。第二个是目前播放的四帧歌曲: 相册艺术品的图像 当前播放歌曲的详细信息(艺人、专辑、曲目等) 按钮(关闭、暂停/播放、洗牌、下一步、上一步等) 树形纪年(最近播放,正在播放,下一个) 如何转换机器语言引用: 转换成人类可读的格式,例如: 这是一个x宽y高的窗

  • 我有一个包含如下值的对象 这些都在变量autossuggest中。现在我只想获得值 谢谢你的小费