TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Python Type: setattr and getattr Examples

These Python 3 examples use type, getattr and setattr. They 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.

Based on:

Python 3

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

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

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)

Output

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)

Output

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf