Home
Python
type: setattr and getattr Examples
This page was last reviewed on Apr 14, 2023.
Dot Net Perls
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.
Info We use setattr to add a field (or attribute) to our class instance. We pass the class instance, the attribute name, and the value.
Next We call getattr to fetch the value of a class's attribute. Here this call returns the value set by setattr.
Cat = type("Cat", (object,), dict()) cat = Cat() # Set weight to 4. setattr(cat, "weight", 10) # Get the weight. value = getattr(cat, "weight") print(value)
10
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.
Dictionary
Then We display these values on a Cat instance. We use the print built-in method.
print
# 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.
Note With delattr we remove an attribute from the class. This is another syntax form for the del operator.
Note 2 We use the del operator to remove things (as from a dictionary). This is a special syntax form.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 14, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.