Python Type: setattr and getattr ExamplesUse type, getattr and setattr. Create types and attributes directly with built-in function calls.
Type. Python supports classes. With the type built-in, we can directly create types. From these types we can instantiate classes.
With setattr we can add attributes (fields) to our classes. With getattr we retrieve those values. We create types with command statements.
First example. This program creates a type with the type built-in. This is an alternative syntax form to the class keyword. We name this type "Cat."
Tip Our type inherits from object, the base class for Python types. And it has no initial attributes.
Setattr We use setattr to add a field (or attribute) to our class instance. We pass the class instance, the attribute name, and the value.
Getattr Next we call getattr to fetch the value of a class's attribute. Here this call returns the value set by setattr.
Python program that uses type
Cat = type("Cat", (object,), dict()) cat = Cat() # Set weight to 4. setattr(cat, "weight", 10) # Get the weight. value = getattr(cat, "weight") print(value)
Dict. We can initialize attributes of a type with a dictionary argument. This is the third argument. Here I set the attribute "paws" to 4, and "weight" to -1.
Tip This is a dictionary instance. It can be created like any other dictionary.
Print We display these values on a Cat instance. We use the print built-in method.
Console, print
Python program that uses dict in type
# Create class type with default attributes (fields). Cat = type("Cat", (object,), {"paws": 4, "weight": -1}) cat = Cat() # Access attributes. print("Paws =", cat.paws) print("Weight =", cat.weight)
Paws = 4 Weight = -1
Hasattr. There are two built-in functions other than getattr and setattr. With hasattr we see if an attribute (field) exists on the class instance. It returns True or False.
Delattr With delattr we remove an attribute from the class. This is another syntax form for the del operator.
Tip We use the del operator to remove things (as from a dictionary). This is a special syntax form.
Python program that uses hasattr, delattr
class Box: pass box = Box() # Create a width attribute. setattr(box, "width", 15) # The attribute exists. if hasattr(box, "width"): print(True) # Delete the width attribute. delattr(box, "width") # Width no longer exists. if not hasattr(box, "width"): print(False)
True False
By understanding type, setattr and getattr, we learn more about how Python classes work. This knowledge helps us write better programs.
Statements in Python, like "class" declarations, can be directly translated to built-in method calls like "type." Low-level parts of the language are used to implement high-level parts.
© 2007-2021 sam allen.
see site info on the changelog.