views:

36

answers:

3

Hi, 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 = "@"
+2  A: 

Are you looking for:

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.

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.

Eli Bendersky
+2  A: 

hasattr(x, 'foo') is a built-in binary function that checks whether object x has an attribute x.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;-).

Alex Martelli
+1  A: 

You could use exception handling to do this as well.

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