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 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

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:

getattr(object, name[,default])

Output:

300

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:

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")

  • 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 faster

  • delattr() is slower but not a huge difference

Last updated