[英]getattr lookup fails for instance of class python
I'm doing an exercise in which you're supposed to calculate a score of how classy your items are. 我正在做一个练习,您应该在其中计算出商品的优雅程度。 A tophat gives you 2 points, a bowtie gives you 4 points and a monocle gives you 5 points. 高顶礼帽给你2分,领结给你4分,单片给你5分。 I've initiated a dictionary with these items on each class instance, yet when I use getattr
to check if the item has the attribute it always returns None
. 我已经在每个类实例上使用这些项目启动了字典,但是当我使用getattr
检查项目是否具有属性时,它始终返回None
。
class Classy(object):
def __init__(self):
self.items = []
self.classyItems = {'tophat': 2, 'bowtie': 4, 'monocle': 5}
def addItem(self, str):
self.items.append(str)
def getClassiness(self):
classiness = 0
for item in self.items:
itemIsClassy = getattr(self.classyItems, item, None) # Why does this always return none?
if itemIsClassy:
classiness += itemIsClassy
else:
pass
return classiness
# Test cases
me = Classy()
# Should be 0
print me.getClassiness()
me.addItem("tophat")
# Should be 2
print me.getClassiness() # I'm getting 0
Why is getattr
returning None
when self.classyItems
clearly has the attribute of tophat? 当self.classyItems
明确具有tophat属性时,为什么getattr
返回None
?
Thanks for the help everyone! 感谢大家的帮助! I was still confused after reading the answer and simply reading that dictionary keys are not attributes here helped me. 阅读答案后,我仍然感到困惑,只是阅读字典键不是这里的属性对我有所帮助。 Is Python dict an Object? Python dict是对象吗?
getattr
accesses attributes and/or methods, but classyItems
is a dict which doesn't have any (visible) attributes 1 and stores its contents as key-value pairs 2 . getattr
访问属性和/或方法,但是classyItems
是不具有任何(可见)属性1的字典,并将其内容存储为键值对2 。
In your case you should use dict.get
instead of getattr
, more specifically self.classyItems.get(item, None)
, to access the values with default. 在您的情况下,应该使用dict.get
而不是getattr
,更具体地说,使用self.classyItems.get(item, None)
来访问默认值。
1 Dictionaries have methods that could be accessed using getattr
though. 1字典具有可以使用getattr
访问的方法。
2 That's why you access them using d[key]
instead of d.key
. 2这就是为什么您使用d[key]
而不是d.key
访问它们的原因。
getattr()
takes an object and a string of the attribute to look for, and returns that object . getattr()
获取一个对象和该属性的字符串 ,然后返回该对象 。 You don't have an attribute named item
in your object, but you do have classyItems
: Using your code you can see that: 您的对象中没有名为item
的属性,但是您有classyItems
:使用您的代码,您可以看到:
>>> getattr(me, 'classyItems')
{'bowtie': 4, 'tophat': 2, 'monocle': 5}
It is much easier (and readable) to use self.classyItems.get(item, None)
which looks up a dict and returns default value. 使用self.classyItems.get(item, None)
会更容易(也更容易理解self.classyItems.get(item, None)
,它可以查找字典并返回默认值。 You can't lookup a dict values with getattr
, but you can however check if it has certain methods: 您不能使用getattr
查找字典值,但是可以检查它是否具有某些方法:
>>> getattr(me.classyItems, 'update')
<built-in method update of dict object at 0x028ADE40>
将itemIsClassy = getattr(self.classyItems, item, None)
替换为itemIsClassy = self.classyItems.get(item, None)
As mentioned by @Dharmesh and @MSeifert, replace itemIsClassy = getattr(self.classyItems, item, None)
to itemIsClassy = self.classyItems.get(item, None)
如@Dharmesh和@MSeifert所述,将itemIsClassy = getattr(self.classyItems, item, None)
替换为itemIsClassy = self.classyItems.get(item, None)
The reason why your code didn't work is not because classyItems
doesn't have many attributes, it is because the getattr
function works on objects, not dictionary. 您的代码不起作用的原因不是因为classyItems
没有太多属性,而是因为getattr
函数对对象起作用,而不对字典起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.