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.
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."
class
for Python types. And it has no initial attributes.class
instance. We pass the class
instance, the attribute name, and the value.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
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.
# 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
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.
class
. This is another syntax form for the del operator.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.