Testing for the existence of a field in a class

Brett picture Brett · Apr 20, 2010 · Viewed 18.2k times · Source

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 = "@"

Answer

Alex Martelli picture Alex Martelli · Apr 20, 2010

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.