Dot notation is a syntax used in programming languages, including Python, to access an object’s attributes and methods. It allows you to easily navigate through complex data structures without having to write long lines of code, which can be incredibly useful for any developer.
Dot Notation Explained
Dot notation is a feature in object-oriented programming languages like Python that allows you to search an extensive database for an object’s attributes and methods. In Python, dot notation is written as: [object we want to access][dot][attribute or method]
.
Just imagine that you’re working on a project that involves managing a large data set of customer information. There are hundreds of thousands of entries. Trawling through that data for the exact customer information your boss asked for would take hours, if not days. This is where dot notation comes in.
Suppose you have information on the name, email, and phone number of each potential customer. With dot notation, you can simply type something like customer.name to access the customer’s name and customer.phone to access the customer’s phone number. Let’s take a look at how this magical bit of code works.
What Is Dot Notation?
Dot notation is a feature in many object-oriented programming (OOP) languages like Python. Within OOP languages, we treat almost every entity like a real-world object. Each object has certain “attributes” that describe its state and certain “methods” that make them behave in a certain way. Suppose we’re creating a customer relationship management system in Python. Our object is the customers. These customers have attributes like their name, email address, phone number and purchase history. A method applied to this object might tell us the first name of the customer.
Dot notation is a way of accessing an object’s attributes and methods. Think of dot notation as a key to open a lock. The lock is the object we want to open. By using the right key (dot notation), we can open the lock to access the object’s attributes and methods.
When we use dot notation in Python, we usually write [object we want to access][dot][attribute or method]. We replace the items in the square brackets with what object, attribute and method we actually want access to. For example, we might write customer.name
to access the name of a customer and customer.previous_purchase
to access information about their last purchase. Combining all this information, we can write a personalized email to the customer, addressing them by their first name and mentioning items that they’ve bought from us in the past.
How to Use Dot Notation in Python
Let’s look at some examples of how dot notation is used in Python.
1. Dot Notation in Strings
Python has certain built-in string methods like .upper()
, which turns a string into its upper-case version, and .replace()
, which replaces letters and words in a string. We can use dot notation to access the built-in string methods.
my_string = "Hello, World!"
print(my_string.upper()) # this prints "HELLO, WORLD!"
print(my_string.replace("Hello", "Goodbye")) # this prints prints "Goodbye, World!"
2. Dot Notation in Lists
Python also has built-in list methods like .append()
, which adds to the list, and .sort()
, which sorts a list in ascending order. We can use dot notation to access built-in list methods.
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
my_list.append(7) # this appends the number 7 to my_list
my_list.sort() # this sorts my list
print(my_list) # this line prints [1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 9]
3. Dot Notation in Custom Objects
We can use dot notation to access attributes and methods of objects that we create. In this example, we define a class Person. Each Person has a name and an age. We access the person’s name using the .name
method, and we get that person to say hello by using the say_hello
method.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
person1 = Person("Alice", 30)
person2 = Person("Bob", 40)
print(person1.name) # Prints "Alice"
person2.say_hello() # Prints "Hello, my name is Bob and I am 40 years old."
4. Dot Notation in Datetime Objects
We can use dot notation to access the properties of datetime objects. Suppose I want to know the current year and month. Here’s a piece of code I could write:
import datetime
now = datetime.datetime.now() # apply now() to get current datetime
print(now.year) # this prints the current year
print(now.month) # this prints the current month
5. Dot Notation in Numpy Arrays
We can use dot notation to access the property and methods of NumPy arrays such as .shape
, which returns the array’s dimensions, and .mean()
, which computes the mean of the values in the array. Let’s create an array with two columns and three rows.
import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6]]) # create your numpy array
print(my_array.shape) # prints (2, 3)
print(my_array.mean()) # prints 3.5
Common Dot Notation Mistakes and Solutions
Sometimes accessing the attributes and methods of an object isn’t as simple as typing [object we want to access][dot][attribute or method]. One of the most common pitfalls is overlooking whether the thing we’re trying to access is a valid Python identifier. If it isn’t a valid Python identifier, using square brackets is your best friend to debug your code. Let’s look at some examples.
First, using square brackets can come in handy when accessing values in a dictionary. Although we can use dot notation to access these values, the keys of the dictionary must be strings and must be valid Python identifiers. If this doesn’t hold, we’ll need to use square bracket notation instead.
my_dict = {"first name": "Alice", "last name": "Smith"}
print(my_dict.first name) # Raises SyntaxError: invalid syntax
print(my_dict["first name"]) # Prints "Alice"
Similarly, if you have a Pandas DataFrame object, you can use dot notation to access the columns only if the column names are valid Python identifiers. Here, “valid” means that they don’t contain any spaces or special characters. If the column names are not valid Python identifiers, you can’t use dot notation and need to use the square bracket notation instead. For example:
import pandas as pd
# Creating a DataFrame with column names that are valid Python identifiers
df1 = pd.DataFrame({'name': ['Alice', 'Bob'], 'age': [30, 40]})
print(df1.name) # Works using dot notation
# Creating a DataFrame with column names that are not valid Python identifiers
df2 = pd.DataFrame({'full name': ['Alice Smith', 'Bob Johnson'], 'age': [30, 40]})
print(df2.full name) # Raises SyntaxError: invalid syntax
# Using square bracket notation is the alternative
print(df2['full name']) # Works using square bracket notation
Lastly, if you have a complex object with nested attributes, such as a dictionary of dictionaries or a class with nested objects, you can’t use dot notation to access the nested attributes directly. Instead, you need to use multiple levels of square bracket notation or a combination of dot notation and square bracket notation. For example:
# Creating a nested dictionary
nested_dict = {'person': {'name': 'Alice', 'age': 30}}
# Using dot notation to access a nested attribute doesn't work
print(nested_dict.person.name) # Raises AttributeError: 'dict' object has no attribute 'person'
# Using square bracket notation to access a nested attribute works
print(nested_dict['person']['name']) # Prints "Alice"
# Alternatively, you can use a combination of dot notation and square bracket notation
print(nested_dict['person'].name) # Also prints "Alice"
Dot Notation Benefits
Dot notation is a crucial concept in object-oriented programming languages like Python. By mastering how to use dot notation, we’ll be able to access an object’s attributes and methods with ease and write code that’s easy to understand and replicable. For the most part, dot notation is simple to use.
But there are applications that require more thought and lines of code, such as when the thing we’re trying to access isn’t a valid Python identifier, or when we’re accessing a nested attribute. In these cases, we’ll need to look for solutions like square bracket notation that allow us to access the object’s attributes and methods in an errorless way.