5 Ways to Control Attributes in Python. An Example Led Guide (2023)

(Video) Python: How to modify an attributes value through a method

What happens at the dot.

Introduction

Data integrity can be secured by controlling attribute values and their access. When a class is created, we may want to ensure all future objects have attributes of the correct data type, and/or of sensible/appropriate values. We may also want to ensure once attributes are set their values cannot be changed or deleted. To achieve this, read-only and deletion proof attributes must be created.

An Employee class, that accepts name, age and length of service as arguments, may want to ensure that the name is a string, and the age and length of service are integers before they are set as attributes in the objects created. This class may also want to ensure attributes like names cannot be altered or deleted.

Attribute validation can help ensure valid data entry, even in cases where the user of a class may input less than ideal user-information, for example, a name in lower case. This tutorial article will explore 5 different ways to ensure attribute validation, namely via magic/dunder methods and decorators. Attribute integrity is important when the attributes themselves are used in methods defined in the class. This is why, before an attribute gets set in an object, its value should be checked.

Example 1: dunder __setattr_, __delattr__

The magic or dunder __setattr_ and__delattr__ methods in Python represent one way the programmer can exert control over attributes. To illustrate, let's initialise a class called Employees. This class will take 3 arguments and set them as attributes in the objects.

To showcase how we can exert control over attributes, let's establish the behaviour we would like to implement for our Employees object.

  1. The _name attributevalue, should be capitalised, regardless of whether the user chooses to input the name attribute in capitalised format or not.
  2. The _name attribute should only be allowed to be set once. The name attribute will become read-only once it is set.
  3. The _age and _service_length attributes should be integers. If they are not a TypeError exception will be raised.
  4. The _name attribute cannot be deleted

dunder __setattr__

The dunder setattr method takes the object and the key and the value we would like to set in the object as arguments. We first check to see if the object with the attribute ‘_name’ already has the attribute, name. If it does, we will raise an AttributeError because we do not want the name attribute to be re-set. In the following elif statement, if the object does not have a name attribute we will set it, and capitalise it using the string title method.

(Video) Python Serial Port Commuincation

The logic in the first if and elif blocks of the setattr method solves points 1 and 2 above. Now, let's check the data type of the age and service length attributes for point number 3.

For both the ‘_age’ and the ‘_service_length’ attributes, we check they are of type int, using the built-in Python isinstance function. If they are of any type besides int, a TypeError exception will be raised.

Finally, let's address point 4, and implement code to prevent the deletion of the name attribute. For the sake of argument, let's assume, that once a name has been set, it cannot be deletion and exists permanently.

As such, when we attempt to del the name attribute from our object, an AttributeError exception will be raised, informing the user, that the attribute cannot be deleted. Under the hood, the del keyword calls the __delattr__ method. Since we have defined it in our class, it will call our custom version of __delattr__. We will however, still permit behaviour which enables the deletion of any other attribute.

To note, in the code snippets shown, we set and delete the attributes as shown below to avoid recursive errors.

The code for our Employee class is shown below via the GitHub gist and available via this link.

To test the custom behaviour we have implemented, let's create an instance of the Employees class and check to see if the name attribute can be set, cannot be re-set, and cannot be deleted. In addition, we can check the type of the age and service length attributes.

Re-setting the name attribute failed and informs the user of why the program terminated.

5 Ways to Control Attributes in Python. An Example Led Guide (3)

When we loop through the dictionary of attributes, and print their type, we can see the age and length of service are of type int.

5 Ways to Control Attributes in Python. An Example Led Guide (4)

Finally, when we try to delete the attribute name, an AttributeError exception is raised, with the string message informing the user that the attribute cannot be deleted.

5 Ways to Control Attributes in Python. An Example Led Guide (5)
(Video) Neural Network In 5 Minutes | What Is A Neural Network? | How Neural Networks Work | Simplilearn

We have now succeeded in enacting the custom behaviour we desired. While these examples are contrived, they do illustrate how we can control attributes using the setattr and delattr methods in Python. If you would like to try the examples shown, the entire code is available via this link.

Alternative ways to control attributes in an object

The following examples represent alternative ways to control attributes in Python. As a proviso, I do not attest to them being the best way to control attributes, rather alternatives means that can add to your arsenal of tools to use in Python.

The section to follow will introduce an example-led guide to using decorators to manage attributes.

Using Decorators

Example 2: Using @staticmethod Decorator

For continuity, the same Employees class will be initialised in the proceeding examples. Here, the staticmethod decorator can be used to check the attribute value in an object. Specifically, here, we want both the age and service_length attribute values to be of type int.

To do this, we can define a data_type_check method in our class, and decorate it with the staticmethod decorator. When the attributes are being set in the init constructor, we call the method data_type_check on our object, and pass in either age or service_length as arguments. If age, and service length are of type int, they will be returned and set as attributes in our object. If they are not of type int, a type error exception will be raised.

One thing that is really nice about using the staticmethod decorator, is its re-usability. If, for example, we added an annual bonus argument to our init method, we could simply call the staticmethod decorator again and pass bonus as an argument.

Example 3: Using a Custom Decorator

Another way to control the value of attributes is via a custom decorator. In keeping with our theme, let's create the same class, but this time decorate the init constructor method, with a function called attr_check.

When we create an instance of our Employee class, the init method will be called automatically. As the attr_check function decorates the init method, this function will be called. attr_check will take the init method as an argument, and return inner. When we then call inner with our object ref, age and service, we can perform type checking on both age and service. If age and service are of type int, we will return the original init method with the object, name, age and service and arguments.

This implementation is a nice way to control attribute values in Python because we can choose what goes into the body of inner. In this case, we did not perform any type checking on the name or any range allowance on the age, but we could simply add these checks in, by expanding the code defined within the inner function.

Example 4: Using the @property/setter/deleter decorators

Yet another way to control attribute values in Python is through the use of the property decorator and its corresponding setter and deleter methods.

Let's create our Employees class once more. When the user attempts to access the name attribute through the object.attribute syntax, the name method decorated with @property will be called, and the name will be returned capitalised.

This time if the user would like to change the name attribute, let's ensure whatever string they input will be capitalised. We can achieve this by defining a simple name method alongside corresponding setter and deleter methods.

We define the name method and decorate it with @name.setter. When the user wants to set a new name, using the object.attribute syntax, the new name set in the object will now be capitalised.

Note, the underlying name of the name attribute ‘_name’, is different to the name of the method to avoid recursive errors. We could not have self.name = new_name.title() in the body of our setter method.

(Video) Tensorflow Object Detection in 5 Hours with Python | Full Course with 3 Projects

Example 5: Conditional checking in the init Constructor

To finish this article on attribute control, the simplest way to implement attribute integrity, may in fact be to include conditional checking in the init constructor of our class itself. Here, we allow the age of the employee to be greater than or equal to 18, and less than or equal to 100. If the condition is satisfied, we can set the age supplied as an argument in the init method as an attribute value in our object. When an instance is created that fails to satisfy this condition, an AttributeError exception is raised, with a useful string message informing the user of the conditions required.

Summary

Thanks for reading, and I hoped you liked the different ways to control attribute access and their values. While I have mainly focused on data-type checking and range allowance, any conditional imaginable can be imposed on an attribute value. An email address may undergo validation using regex before being set, to comply with data integrity.

I have deliberately used basic examples here to help convey how the multiple ways to control attribute values and access work. Furthermore, Descriptors are another way to manage attributes in Python, and I will hopefully write a tutorial piece on how to use them. If you have any questions, or would like more articles themed around this topic, let me know via LinkedIn.

FAQs

What are attributes in Python with example? ›

Instance attributes are defined inside the __init__ method.
...
Example:
  • class Student_info:
  • def __init__(self, name, age, college):
  • self.name = name;
  • self. age = age;
  • self. college = college;
  • student1 = Student_info("Ryan", 18, "NYU")
  • student2 = Student_info("Roy", 18, "Duke")
  • print("Student1: ")

What are different types of attributes in Python? ›

There are two kinds of valid attribute names: data attributes and methods. The other kind of instance attribute reference is a method. A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well.

Which are the three key attributes of Python object? ›

Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. Instantiation − The creation of an instance of a class. Method − A special kind of function that is defined in a class definition.

Which method is used to set attribute in Python? ›

Python setattr() method is used to assign the object attribute its value.

What are four main types of data attributes one example for each? ›

Different types of attributes or data types:
  • Nominal Attribute: ...
  • Ordinal Attribute: ...
  • Binary Attribute: ...
  • Numeric attribute:It is quantitative, such that quantity can be measured and represented in integer or real values ,are of two types.
Sep 27, 2022

What are some examples of attribute data? ›

Attribute data is defined as a type of data that can be used to describe or quantify an object or entity. An example of attribute data is things like coluor, , yes/no, gender, etc. This type of data is typically used in conjunction with other forms of data to provide additional context and insights.

How many types of attribute are there? ›

There are six such types of attributes: Simple, Composite, Single-valued, Multi-valued, and Derived attribute.

What are attribute types? ›

An attribute type definition specifies the attribute's syntax and how attributes of that type are compared and sorted. The attribute types in the directory form a class hierarchy. For example, the "commonName" attribute type is a subclass of the "name" attribute type.

What are data attributes in Python? ›

Also, data attributes are, simply said, variables bound to an object, where method attributes (methods) are functions bound to an object.

What are properties and attributes in Python? ›

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.

What are the three attributes of an object? ›

Every object has associated prototype, class, and extensible attributes.

What are the 3 common data types used in Python? ›

You'll learn about several basic numeric, string, and Boolean types that are built into Python.

What are attributes and methods in programming? ›

Any variable that is bound in a class is a class attribute . Any function defined within a class is a method . Methods receive an instance of the class, conventionally called self , as the first argument.

What is attribute also called in Python? ›

An attribute that belongs to an instance of the object is called as an instance attribute. Let us discuss more. An attribute that is declared and initialized inside the __init__() method of any class is known as a Python instance attribute.

How do you get attributes in Python? ›

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

What are the examples of simple attributes? ›

Simple attributes are those that cannot be further divided into sub-attributes. For example, A student's roll number of a student or the employee identification number. These attributes are usually assigned by an organization and are used to identify an individual within that organization uniquely.

What is an attribute explain the types of attributes with examples for each? ›

Attributes are properties which describes each member of an entity set. For example, an EMPLOYEE entity may be described by the employee's name, age, address, salary, and job. A particular entity will have a value for each of its attributes and hence forms major part of data stored in database.

What are four attributes of a variable? ›

Techopedia Explains Variable

A variable is assigned a value in one place and then used repetitively. Variables generally have four attributes: an identifier, data location, type and value.

What are the 5 attributes of data? ›

There are five traits that you'll find within data quality: accuracy, completeness, reliability, relevance, and timeliness – read on to learn more. Is the information correct in every detail?

What is an attributes in programming example? ›

Attributes can be defined as characteristics of system entities. For example, CPU Speed and Ram Size can be defined as computer attributes.

What is an example of attribute and variable data? ›

If the park measured each child's height when they walked into the park, that would be considered variable data. However, checking if a child is above the “Must be taller than this to ride” sign would be attribute data.

What are the 4 types of attributes? ›

Types of attributes
  • Single valued Attribute. Attributes having a single value for a particular item is called a single valued attribute. ...
  • Multi-valued Attribute. Attribute having a set of values for a single entity is called a multi-valued attribute. ...
  • Derived Attributes or stored Attributes. ...
  • Complex Attribute.
Jul 3, 2021

What is a key attribute? ›

Definition(s):

A distinct characteristic of an object often specified in terms of their physical traits, such as size, shape, weight, and color, etc., for real -world objects. Objects in cyberspace might have attributes describing size, type of encoding, network address, etc.

What are standard attribute names 3? ›

Standard attributes are also known as global attributes, and function with a large number of elements. They include the basic standard attributes: these include accesskey, class, contenteditable, contextmenu, data, dir, hidden, id, lang, style, tabindex, title.

What is attribute in programming? ›

In computing and computer programming, an attribute is a changeable property or characteristic of some component of a program that can be set to different values.

What are the two types of attribute data? ›

Types of Attribute Data
  • (I) Nominal Data: - Nominal data describe different kinds of different categories of data such as land use types or soil types.
  • (II) Ordinal Data: - Ordinal data differentiate data by ranking relationship.
Sep 28, 2012

How many attributes are there in Python? ›

Introduction. A Python object has two types of attributes: Class Attribute and Instance Attribute. As the above example, class_attr is a class attribute and self.

What are attribute properties? ›

An object characteristic that is always present and occupies storage, even if the attribute does not have a value. In this respect, an attribute is similar to a field in a fixed-length data structure. A distinguishing feature of attributes is that each attribute has its own methods for setting and getting its value.

What are the five basic attributes of a managed object type? ›

i) The five basic attributes of a managed object type from the Internet perspective are name, definition, syntax, access, and status.

What are the attributes and methods of an object? ›

Attributes - things that the object stores data in, generally variables. Methods - Functions and Procedures attached to an Object and allowing the object to perform actions.

What are the attributes of an object called? ›

An attribute of an object usually consists of a name and a value; of an element, a type or class name; of a file, a name and extension.

What are the 5 main data types used in Python? ›

Python Data Types
  • Python Numeric Data Type. Python numeric data type is used to hold numeric values like; ...
  • Python String Data Type. The string is a sequence of characters. ...
  • Python List Data Type. The list is a versatile data type exclusive in Python. ...
  • Python Tuple. ...
  • Python Dictionary.
Aug 3, 2022

What are the five standard data types in Python? ›

Python has five standard Data Types:
  • Numbers.
  • String.
  • List.
  • Tuple.
  • Dictionary.
Dec 12, 2018

What are the 6 data types in Python? ›

Python has six standard Data Types:

List. Tuple. Set. Dictionary.

Has attribute Python function? ›

Python hasattr() Function

The hasattr() function returns True if the specified object has the specified attribute, otherwise False .

How do you set an attribute to an object in Python? ›

The setattr() function sets the value of the attribute of an object.
...
The setattr() function takes three parameters:
  1. object - object whose attribute has to be set.
  2. name - attribute name.
  3. value - value given to the attribute.

How do you get attributes of a class in Python? ›

Accessing the attributes of a class
  1. getattr() − A python method used to access the attribute of a class.
  2. hasattr() − A python method used to verify the presence of an attribute in a class.
  3. setattr() − A python method used to set an additional attribute in a class.
Jun 30, 2020

How do you get attribute values? ›

The getAttribute() method is used to get the value of an attribute of the particular element. If the attribute exists, it returns the string representing the value of the corresponding attribute. If the corresponding attribute does not exist, it will return an empty string or null.

What is an attribute in Python class? ›

Python class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class and are not shared between instances.

What is attribute in Python module? ›

Python module has its attributes that describes it. Attributes perform some tasks or contain some information about the module.

What are attributes in coding? ›

In computing and computer programming, an attribute is a changeable property or characteristic of some component of a program that can be set to different values.

What is an attribute and its types with examples? ›

An attribute is a property or characteristic of an entity. An entity may contain any number of attributes. One of the attributes is considered as the primary key. In an Entity-Relation model, attributes are represented in an elliptical shape. Example: Student has attributes like name, age, roll number, and many more.

Which of type Following is example of attribute? ›

There are different types of attributes in DBMS: Simple, Composite, Single Valued, Multi-Valued, Stored, Derived, Key, and Complex attributes. Simple attributes can't be further subdivided into any other component, and hence, they are also known as atomic attributes.

How do I find attributes in Python? ›

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

Videos

1. Raspberry Pi Pico - Control the (I/O) World
(DroneBot Workshop)
2. 5 Basic Networking commands for everyone (2023) | How to troubleshoot network issues on Windows?
(IT k Funde)
3. Program in Python to Control LED using Push button Switch, Rocker switch and CISCO Packet Tracer
(Sreenivasa Setty)
4. EasyEDA Full TUTORIAL + Create Component + TIPS
(Electronoobs)
5. CircuitPython Tutorial
(Derek Banas)
6. Tkinter Course - Create Graphic User Interfaces in Python Tutorial
(freeCodeCamp.org)
Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated: 03/15/2023

Views: 6216

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.