测试类中某个字段是否存在
我有一个简单的问题。我有一个存储类实例的二维数组。根据程序前面读取的文本文件,为数组的元素分配一个特定的类。由于如果不查看文件,我就不知道特定元素中存储了什么类,所以我可以引用该索引中不存在的字段(指在该索引中存储 temp 实例时的外观)。我想出了一种测试方法,但它很冗长并且需要第二个矩阵。是否有一个函数可以测试类中某个字段是否存在?
class temp():
name = "default"
class temp1():
appearance = "@"
i have a quick question. I have a 2D array that stores an instance of a class. The elements of the array are assigned a particular class based on a text file that is read earlier in the program. Since i do not know without looking in the file what class is stored at a particular element i could refer to a field that doesn't exist at that index (referring to appearance when an instance of temp is stored in that index). i have come up with a method of testing this, but it is long winded and requires a second matrix. Is there a function to test for the existence of a field in a class?
class temp():
name = "default"
class temp1():
appearance = "@"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
hasattr(x, 'foo')
是一个内置的二进制函数,用于检查对象x
是否具有属性x.foo
(是否从它的类中获取它与否),这似乎与您所要求的很接近。您所问的是否实际上是您应该问的则是另一个问题 - 正如@ Eli 的答案表明,你的设计看起来很奇怪。但是,这确实回答了您提出的问题。hasattr(x, 'foo')
is a built-in binary function that checks whether objectx
has an attributex.foo
(whether it gets it from its class or not), which seems close to what you're asking. Whether what you're asking is actually what you should be asking is a different issue -- as @Eli's answer suggests, your design seems strange. However, this does answer your question as asked.您是否在寻找:
无论你想做什么似乎都不是一个好主意。请更详细地描述您的原始需求,我们将帮助您提出更好的设计。
Are you looking for:
Whatever you're trying to do doesn't seem like a good idea. Please describe your original need in more detail, and we'll help you come up with a better design.
您也可以使用异常处理来执行此操作。
You could use exception handling to do this as well.