C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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)
Output
10
Tip: This is a dictionary instance. It can be created like any other dictionary.
DictionaryPrint: We display these values on a Cat instance. We use the print built-in method.
Console, printPython 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)
Output
Paws = 4
Weight = -1
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)
Output
True
False