hasattr(), getattr(), delattr()
Last updated
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 brand variable 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 porsche instance
The above example is correct
After that it will return True
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
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:
Key difference is that it has () at the end of the getattr function
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
Output will print a messy output of __dict__ but the hp attribute will not be found
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:
del is faster
delattr() is slower but not a huge difference
Last updated
getattr(object, name[,default])300print(getattr(Jeep, 'modelllll', '4x4'))print(getattr(Jeep, 'modelllll', None))delattr(object, 'string')