类中字段存在性的测试

2024-06-23 19:06:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个简短的问题。我有一个二维数组,它存储一个类的实例。数组的元素根据程序中前面读取的文本文件被分配到一个特定的类。因为我不知道在文件中什么类存储在一个特定的元素中,所以我可以引用一个在该索引中不存在的字段(引用temp实例存储在该索引中时的外观)。我已经提出了一种测试方法,但它是冗长的,需要第二个矩阵。类中是否有用于测试字段存在性的函数?

class temp():
   name = "default"

class temp1():
   appearance = "@"

Tags: 文件实例函数name程序default元素矩阵
3条回答

您也可以使用异常处理来执行此操作。

try:
    val = x.name
except AttributeError:
    val = x.appearance

你在找:

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct or indirect) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

不管你想做什么似乎都不是个好主意。请详细描述您最初的需求,我们将帮助您设计出更好的设计。

hasattr(x, 'foo')是一个内置的二进制函数,用于检查对象x是否具有属性x.foo(是否从其类中获取),这似乎与您的要求很接近。你所问的是不是你应该问的是一个不同的问题——正如@Elianswer所建议的,你的设计看起来很奇怪。不过,这确实回答了你提出的问题。

相关问题 更多 >

    热门问题