hasattr(), getattr(), delattr()
Check if a python Object has an Attribute
hasattr():
Syntax:
hasattr(object, string)- 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 - brandvariable is not assigned so this has to be passed in as a string- NameError: name 'brand' is not defined
 
- You need to pass the brand variable to the - porscheinstance
- The above example is correct 
- After that it will return - True
Checking methods:
- This will still return - Trueas 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:
getattr(object, name[,default])Output:
300If you print the model attribute then it will print the string Wragler
If the attribute does not exist you can return a default mode:
print(getattr(Jeep, 'modelllll', '4x4'))Output: 4x4
One super helpful paramteter for this is the keyword None:
print(getattr(Jeep, 'modelllll', 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 to- del
Syntax:
delattr(object, 'string')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()?
- delis faster
- delattr()is slower but not a huge difference
Last updated