问题
I have a class, user
, that has an attribute metadata
.
metadata
is a list of objects, each with different classes, for example:
user.metatada = [Employee(), Student(), OtherClass()]
In an update script, I need to check, if a certain type exists in a list, like so:
if type(Employee()) in user.metadata:
replace user.metadata[indexOfThatEmployee] with new Employee()
else:
user.metadata.append(new Employee())
is there anyway to easily to check if a certain type exists in a list?
回答1:
Got it.
test = [Employee()]
if any(isinstance(x, Employee) for x in user.metadata):
user.metadata = [x for x in user.metadata if not isinstance(x, Employee)] + test
else:
user.metadata = user.metadata + test
So this will check if there exists an object in the list that is an instance of the Employee class, if so, filter the list of the existing Employee object and add in the new one, if it doesn't exist, just add it in.
来源:https://stackoverflow.com/questions/50501346/how-to-see-if-a-certain-class-exists-in-a-list