Python:从对象获取具有整数名称的属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python:从对象获取具有整数名称的属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2692字,纯文字阅读大概需要4分钟。
内容图文
![Python:从对象获取具有整数名称的属性](/upload/InfoBanner/zyjiaocheng/787/0b2a660f2e7c42bb95094a887b28e135.jpg)
我最近发现我可以用Python做到这一点:
>>> obj = type("SomeObj", (), {1: "a", 2: "b", 3: "c"})()
>>> obj
<__main__.SomeObj object at 0x123456789>
对象obj肯定具有属性1,2和3,如dir()所示:
>>> dir(obj)
[1, 2, 3, '__class__', '__delattr__', '__dict__', ...]
但是,我无法检索三个属性之一的值.
>>> obj.1
File "<stdin>", line 1
obj.1
^
SyntaxError: invalid syntax
>>> getattr(obj, "1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'ObjectifiedDict' object has no attribute '1'
>>> obj.__getattribute__(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: attribute name must be string, not 'int'
有没有办法做到这一点?
我知道使用整数作为属性名称通常是一个坏主意,它只是让我很好奇.
解决方法:
您正在将一个dict传递给可以使用int作为键的类型,没有检入类型以查看您是否传递了有效的name,因此您在稍后尝试访问该属性时会遇到SyntaxError:
Identifiers (also referred to as names) are described by the following >lexical definitions:
identifier ::= (letter|”“) (letter | digit | ““)*
必须将该属性作为字符串传递给hasattr和getattr,其中在尝试查找之前会引发异常.
PyDoc_STRVAR(hasattr_doc,
"hasattr(object, name) -> bool\n\nReturn whether the object has an attribute with the given name.\n(This is done by calling getattr(object, name) and catching exceptions.)");
PyDoc_STRVAR(getattr_doc,
"getattr(object, name[, default]) -> value\n\nGet a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\nWhen a default argument is given, it is returned when the attribute doesn't\nexist; without it, an exception is raised in that case.");
if (!PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"hasattr(): attribute name must be string");
return NULL;
}
if (!PyString_Check(name)) {
PyErr_SetString(PyExc_TypeError,
"getattr(): attribute name must be string");
return NULL;
}
由于上面列出的原因,整数作为属性名称通常是一个坏主意应该是不可能的.
你还会得到一个TypeError:unorderable类型:int()< str()使用python 3中的dir作为属性进行排序:
PyDoc_STRVAR(dir_doc,
"dir([object]) -> list of strings\n"
"\n"
"If called without an argument, return the names in the current scope.\n"
"Else, return an alphabetized list of names comprising (some of) the attributes\n"
"of the given object, and of attributes reachable from it.\n"
"If the object supplies a method named __dir__, it will be used; otherwise\n"
"the default dir() logic is used and returns:\n"
" for a module object: the module's attributes.\n"
" for a class object: its attributes, and recursively the attributes\n"
" of its bases.\n"
" for any other object: its attributes, its class's attributes, and\n"
" recursively the attributes of its class's base classes.");
内容总结
以上是互联网集市为您收集整理的Python:从对象获取具有整数名称的属性全部内容,希望文章能够帮你解决Python:从对象获取具有整数名称的属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。