I want to check whether an object has an attribute as a direct (ie not inherited) property, similar to Javascript's obj.hasOwnProperty()
. How can I do this in Python? hasattr()
seems to return inherited attributes as well.
Have you tried using "in"?
If you have a class object you can check if an attribute was defined by:
"what_you_want_to_search" in object.__dict__
In python you can try using if/in. eg obj = {"a": 1, "b":2, "c":3}
if "a" in obj: your code.
please ref https://www.w3schools.com/python/gloss_python_check_if_dictionary_item_exists.asp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.