Skip to content

Python dot notation

  • by

Python dot notation is a way to access the attribute and methods of each method of instances of different object classes.

Python dot notation examples

A simple example code creates a class with multiple methods and then uses the (.) notation to access those methods.

class Person():
def __init__(self, name, age):
self.name = name
self.age = age

def sayHello(self):
print("Hello, World")

def sayName(self):
print(f"My name is {self.name}")


# Create an object
p = Person("Tim Steve", 50)

# Checking attributes
print("Name of the person: " + p.name)
print("Age of the person: " + str(p.age) + " Years")

# Accessing the attributes
p.sayHello()
p.sayName()

Output:

Python dot notation examples

Here are some examples with dot notations

Index of a list

words = ['godzilla', 'darkness', 'leaving heaven']

# Getting the index of the list
print(words.index('godzilla'))

Splitting a string

pun = "A random string"

print(pun.split())

How to use dot notation for dict in Python?

Answer: Use SimpleNamespace with Namespace. Adding, modifying, and removing values is achieved with regular attribute access, i.e. you can use statements like n.key = val and del n.key.

A simple namespace was added in Python 3.3. For older versions of the language, argparse.Namespace has similar behavior.

from types import SimpleNamespace
import namespace as namespace

d = {'key1': 'value1', 'key2': 'value2'}
n = SimpleNamespace(**d)
print(n)

namespace(key1='value1', key2='value2')
print(n.key2)

Output:

namespace(key1=’value1′, key2=’value2′)
value2

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *