简体   繁体   English

知道名称,获取obj属性的值

[英]Get the value of an obj attribute knowing its name

I have a number of constants,variable in which i keep names. 我有许多常量,其中的变量都保留名字。

ATTR_ITEM_NAME = 'pro'

I check if the attribute is attached to an objects: 我检查属性是否附加到对象:

 if hasattr(obj1, ATTR_ITEM_NAME):

then if exist I want the attribute value to be passed to an attribute of an object, something like this: 那么如果存在,我希望将属性值传递给对象的属性,如下所示:

obj2.fm = obj1.ATTR_ITEM_NAME

ATTR_ITEM_NAME being a string and not an attribute is an error, I need something that works; ATTR_ITEM_NAME是字符串而不是属性是错误,我需要一些有效的方法;

Python also has getattr which works like hasattr but returns the value: Python也有getattr ,它类似于hasattr但返回值:

obj2.fm = getattr(obj1, ATTR_ITEM_NAME)

If you are not sure the attribute exists you could: 如果不确定该属性是否存在,则可以:

  • assign a default value (eg None ) 分配一个默认值(例如None

     DEFAULT = None obj2.fm = getattr(obj1, ATTR_ITEM_NAME, DEFAULT) 
  • or catch the exception using 或使用捕获异常

     try: obj2.fm = getattr(obj1, ATTR_ITEM_NAME) except AttributeError: pass # or do something else... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM