Do python classes have properties?
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Managing Attributes With Python's property() Show
With Python’s Properties are arguably the most popular way to create managed attributes quickly and in the purest Pythonic style. In this tutorial, you’ll learn how to:
You’ll also write a few practical examples that use Managing Attributes in Your ClassesWhen you define a class in an object-oriented programming language, you’ll probably end up with some instance and class attributes. In other words, you’ll end up with variables that are accessible through the instance, class, or even both, depending on the language. Attributes represent or hold the internal state of a given object, which you’ll often need to access and mutate. Typically, you have at least two ways to manage an attribute. Either you can access and mutate the attribute directly or you can use methods. Methods are functions attached to a given class. They provide the behaviors and actions that an object can perform with its internal data and attributes. If you expose your attributes to the user, then they become part of the public API of your classes. Your user will access and mutate them directly in their code. The problem comes when you need to change the internal implementation of a given attribute. Say you’re working on a Now suppose that you have an important user that comes to you with a new requirement. They don’t want At this point, removing Programming languages such as Java and C++ encourage you to never expose your attributes to avoid this kind of problem. Instead, you should provide getter and setter methods, also known as accessors and mutators, respectively. These methods offer a way to change the internal implementation of your attributes without changing your public API. In the end, these languages need getter and setter methods because they don’t provide a suitable way to change the internal implementation of an attribute if a given requirement changes. Changing the internal implementation would require an API modification, which can break your end users’ code. The Getter and Setter Approach in PythonTechnically, there’s nothing that stops you from using getter and setter methods in Python. Here’s how this approach would look:
In this example, you create To access and mutate the value of either Here’s how you can work with >>>
With The Pythonic ApproachEven though the example you just saw uses the Python
coding style, it doesn’t look Pythonic. In the example, the getter and setter methods don’t perform any further processing with >>>
This code uncovers a fundamental principle. Exposing attributes to the end user is normal and common in Python. You don’t need to clutter your classes with getter and setter methods all the time, which sounds pretty cool! However, how can you handle requirement changes that would seem to involve API changes? Unlike Java and C++, Python provides handy tools that allow you to change the underlying implementation of your attributes without changing your public API. The most popular approach is to turn your attributes into properties. Properties represent an intermediate functionality between a plain attribute (or field) and a method. In other words, they allow you to create methods that behave like attributes. With properties, you can change how you compute the target attribute whenever you need to do so. For example, you can turn both The main advantage of Python properties is that they allow you to expose your attributes as part of your public API. If you ever need to change the underlying implementation, then you can turn the attribute into a property at any time without much pain. In the following sections, you’ll learn how to create properties in Python. Getting Started With Python’s property()Python’s With Here’s the full signature of
The first two arguments take function objects that
will play the role of getter (
The return value of You can use
You can use Creating Attributes With property()You can create a property by calling The following example shows how to create a
In this code snippet, you create
Once you have these three methods in place, you create a class attribute called In this example, you use keyword arguments to improve the code readability and prevent confusion. That way, you know exactly which method goes into each argument. To give >>>
The Besides using regular named functions to provide getter methods in your properties, you can also use Here’s a version of >>>
If the functionality of your getter method is limited to just returning the current value of the managed attribute, then using a Properties are class attributes that manage instance attributes. You can think of a property as a collection of methods bundled together. If you inspect >>>
You can access the getter, setter, and deleter methods in a given property through the corresponding Properties are also overriding descriptors. If you use The default implementation of Using property() as a DecoratorDecorators are everywhere in Python. They’re functions that take another function as an argument and return a new function with added functionality. With a decorator, you can attach pre- and post-processing operations to an existing function. When Python 2.2
introduced The decorator syntax consists of placing the name of the
decorator function with a leading
In this code fragment,
The final line of code reassigns the name Python’s
This code looks pretty different from the getter and setter methods approach. The decorator approach for creating properties requires
defining a first method using the public name for the underlying managed attribute, which is Lines 13 to 16 define the setter method for >>>
Besides When you decorate the second The mechanism to define the deleter method is similar. This time, you need to use the Finally, how can you provide suitable docstrings for your properties when you use the decorator
approach? If you check The new >>>
You don’t need to use a pair of parentheses for calling Here’s a recap of some important points to remember when you’re creating properties with the decorator approach:
Up to this point, you’ve created managed attributes using In general, you should avoid turning attributes that don’t require extra processing into properties. Using properties in those situations can make your code:
Unless you need something more than bare attribute access, don’t write properties. They’re a waste of CPU time, and more importantly, they’re a waste of your time. Finally, you should avoid writing explicit getter and setter methods and then wrapping them in a
property. Instead, use the Providing Read-Only AttributesProbably the most elementary use case of
Here, you store the input arguments in the attributes Now you have two read-only properties, >>>
Here, You can take this implementation of
In this example, you define a custom exception called Creating Read-Write AttributesYou can also use Say you want your
Here, you create a There is a subtle detail to note in this new implementation of Why? Because you need to make sure that every value provided as a radius, including the initialization value, goes through the setter method and gets converted to a floating-point number.
Here’s
how your >>>
Both Providing Write-Only AttributesYou can also create write-only attributes by tweaking how you implement the getter method of your properties. For example, you can make your getter method raise an exception every time a user accesses the underlying attribute value. Here’s an example of handling passwords with a write-only property:
The initializer of >>>
In this example, you create In the setter method of Putting Python’s property() Into ActionSo far, you’ve learned how to use Python’s In the following sections, you’ll code
a few examples that will help you get a better practical understanding of common use cases of Validating Input ValuesOne of the most common use cases of Python’s Here’s an implementation of
The setter methods of It’s important to note that assigning the Here’s how your >>>
If you assign This implementation of That’s it! You have repetitive code that follows specific patterns. This repetition breaks the DRY (Don’t Repeat Yourself) principle, so you would want to refactor this code to avoid it. To do so, you can abstract out the repetitive logic using a descriptor:
Now your code is a bit shorter. You managed to remove repetitive
code by defining In general, if you find yourself copying and pasting property definitions all around your code or if you spot repetitive code like in the example above, then you should consider using a proper descriptor. Providing Computed AttributesIf you need an attribute that builds its value dynamically whenever you access it, then The main reason for creating eager attributes is to optimize computation costs when you access the attribute often. On the other hand, if you rarely use a given attribute, then a lazy property can postpone its computation until needed, which can make your programs more efficient. Here’s
an example of how to use
In this example, the Another common use case of properties is to provide an auto-formatted value for a given attribute:
In this
example, As a final example of computed attributes, say you have a Here’s a Cartesian coordinates
This example shows how to compute the distance and angle of a given >>>
When it comes to providing computed or lazy attributes, Caching Computed AttributesSometimes you have a given computed attribute that you use frequently. Constantly repeating the same computation may be unnecessary and expensive. To work around this problem, you can cache the computed value and save it in a non-public dedicated attribute for further reuse. To prevent unexpected behaviors, you need to think of the mutability of the input data. If you have a property that computes its value from constant input values, then the result will never change. In that case, you can compute the value just once:
Even though this implementation of >>>
In these examples, you create a circle with a radius equal to If the input data for a computed attribute mutates, then you need to recalculate the attribute:
The setter method of the >>>
Cool! Another option to create cached properties is to use
Here,
>>>
When you access If you want to create a cached property that doesn’t allow modification, then you can use
This code stacks >>>
In these examples, when you try to assign a new value to Logging Attribute Access and MutationSometimes
you need to keep track of what your code does and how your programs flow. A way to do that in Python is to use If you ever need to keep track of how and when you access and mutate a given attribute, then you can take advantage of
Here, you first import Here’s how you can use >>>
Logging useful data from attribute access and mutation can help you debug your code. Logging can also help you identify sources of problematic data input, analyze the performance of your code, spot usage patterns, and more. Managing Attribute DeletionYou can also create properties that implement deleting functionality. This might be a rare use case of Say you’re implementing your own tree data type. A tree is an abstract data type that stores elements in a hierarchy. The tree components are commonly known as nodes. Each node in a tree has a parent node, except for the root node. Nodes can have zero or more children. Now suppose you need to provide a way to delete or clear the list of children of a given node. Here’s an example that implements a tree node that uses
In this example, >>>
Here, you first create a Creating Backward-Compatible Class APIsAs you already know, properties turn method calls into direct attribute lookups. This feature allows you to create clean and Pythonic APIs for your classes. You can expose your attributes publicly without the need for getter and setter methods. If you ever need to modify how you compute a given public attribute, then you can turn it into a property. Properties make it possible to perform extra processing, such as data validation, without having to modify your public APIs. Suppose you’re creating an
accounting application and you need a base class to manage currencies. To this end, you create a
This class looks clean and Pythonic. Now say that your requirements change, and you decide to store the total number of cents instead of the units and cents. Removing In this situation,
Now your class stores the total number of cents instead of independent units and cents. However, your users can still access and mutate When you write something upon which many people are going to build, you need to guarantee that modifications to the internal implementation don’t affect how end users work with your classes. Overriding Properties in SubclassesWhen you create Python classes that include properties and release them in a package or library, you should expect your users to do a lot of different things with them. One of those things could be subclassing them to customize their functionalities. In these cases, your users have to be careful and be aware of a subtle gotcha. If you partially override a property, then you lose the non-overridden functionality. For example, suppose you’re coding an
In >>>
Great! >>>
What happened? Well, when you override an existing property from a parent class, you override the whole functionality of that property. In this example, you reimplemented the getter method only. Because of that, The idea is that if you ever need to override a property in a subclass, then you should provide all the functionality you need in the new version of the property at hand. ConclusionA property is a special type of class member that provides functionality that’s somewhere in between regular attributes and methods. Properties allow you to modify the implementation of instance attributes without changing the public API of the class. Being able to keep your APIs unchanged helps you avoid breaking code your users wrote on top of older versions of your classes. Properties are the Pythonic way to create managed attributes in your classes. They have several use cases in real-world programming, making them a great addition to your skill set as a Python developer. In this tutorial, you learned how to:
You also wrote several practical examples that walked you through the most common use cases of Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Managing Attributes With Python's property() What are the properties of class in Python?Class Properties
The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.
What does a Python class contain?Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
How do I see the attributes of a class in Python?Method 1: To get the list of all the attributes, methods along with some inherited magic methods of a class, we use a built-in called dir() . Method 2: Another way of finding a list of attributes is by using the module inspect .
What are the properties of a class?The collection of properties assigned to a class defines the class. A class can have multiple properties. For example, objects classified as computers have the following properties: Hardware ID, Manufacturer, Model, and Serial Number.
|