Properties, Attributes, and Different Types of Methods for Objects
Explore the use of underscores and properties in Python.
We'll cover the following...
All of the properties and functions of an object are public in Python, which is different from other languages where properties can be public, private, or protected. That is, there is no point in preventing caller objects from invoking any attributes an object has. This is another difference compared to other programming languages in which we can mark some attributes as private or protected.
There is no strict enforcement, but there are some conventions. An attribute that starts with an underscore is meant to be private to that object, and we expect that no external agent calls it (but again, nothing is preventing this).
Before jumping into the details of properties, it's worth mentioning some traits of underscores in Python, understanding the convention, and the scope of attributes.
Underscores in Python
There are some conventions and implementation details that make use of underscores in Python, which is an interesting topic that's worthy of analysis.
Like we mentioned previously, by default, all attributes of an object are public. Consider the following example to illustrate this:
class Connector:def __init__(self, source):self.source = sourceself._timeout = 60conn = Connector("postgresql://localhost")print(conn.source)print(conn._timeout)print(conn.__dict__)
Here, a Connector
object is created with source
, and it starts with two attributes—the aforementioned source
and timeout
. The former is public and the latter private. However, as we can see from the updated code below, when we create an object like this, we can actually access both of them.
The interpretation of this code is that _timeout
should be accessed only within Connector
itself and never from a caller. This means that we should organize the code in a way so that we can safely refactor the timeout at all of the times it's needed, relying on the fact that it's not being called from outside the object (only internally), hence preserving the same interface as ...