How do these functions work?

Here’s a brief overview of how each of these functions works:

  1. getattr(object, name[, default]):

    • This function retrieves the value of the named attribute from the given object.
    • If the attribute does not exist, it returns the value specified by the default parameter if provided; otherwise, it raises an AttributeError.
    • Example:
      class MyClass:
          def __init__(self):
              self.attribute = 'value'
      
      obj = MyClass()
      print(getattr(obj, 'attribute'))  # Output: value
      print(getattr(obj, 'nonexistent', 'default'))  # Output: default
  2. setattr(object, name, value):

    • This function sets the value of the named attribute on the given object.
    • If the attribute does not exist, it creates it.
    • Example:
      class MyClass:
          pass
      
      obj = MyClass()
      setattr(obj, 'attribute', 'value')
      print(obj.attribute)  # Output: value
  3. delattr(object, name):

    • This function deletes the named attribute from the given object.
    • If the attribute does not exist, it raises an AttributeError.
    • Example:
      class MyClass:
          def __init__(self):
              self.attribute = 'value'
      
      obj = MyClass()
      delattr(obj, 'attribute')
      # print(obj.attribute)  # This would raise an AttributeError
  4. hasattr(object, name):

    • This function checks if the named attribute exists on the given object.
    • It returns True if the attribute exists, and False otherwise.
    • Example:
      class MyClass:
          def __init__(self):
              self.attribute = 'value'
      
      obj = MyClass()
      print(hasattr(obj, 'attribute'))  # Output: True
      print(hasattr(obj, 'nonexistent'))  # Output: False

These functions are useful for dynamic attribute manipulation in Python objects.

0 Comments

no data
Be the first to share your comment!