hasattr(), getattr(), delattr()
Check if a python Object has an Attribute
hasattr():
Syntax:
Object (=instance) you want to check for the attribute
String that is the name of the attribute
Boolean (True, False)
The above example will lead to an error as the
brand
variable is not assigned so this has to be passed in as a stringNameError: name 'brand' is not defined
You need to pass the brand variable to the
porsche
instanceThe above example is correct
After that it will return
True
Checking methods:
This will still return
True
as python uses methods simillar to attributes (Object)There is no implicit difference between a method and an attribute (Object) as:
A method if basically a function which is an Object
getattr():
Syntax:
Output:
If you print the model
attribute then it will print the string Wragler
If the attribute does not exist you can return a default mode:
Output: 4x4
One super helpful paramteter for this is the keyword None
:
To print out functions
Key difference is that it has
()
at the end of the getattr function
delattr():
Does not work to delete the key from a dictionary
Basically does not work on dictionaries at all
Used to delete the attributes
delattr()
is the equivalant todel
Syntax:
Output will print a messy output of __dict__
but the hp
attribute will not be found
There is an additional parameter attr.startswith("string")
attr.startswith("string")
This allows you to check if an attribute starts with something
Useful if you want to get rid of the dunder methods within the
__dict__
print statement:
Which is better del or delattr()?
del
is fasterdelattr()
is slower but not a huge difference
Last updated