Skip to content

Python dot operator

  • by

In Python, the dot operator (.) is used to access attributes and methods of objects. It is also known as the attribute access operator or the dot notation.

When you have an object, you can use the dot operator to access its attributes and methods. An attribute is a variable associated with an object, while a method is a function associated with an object.

The syntax for the dot operator is as follows:

object_name.attribute_name
object_name.method_name()
module_name.attribute_name
module_name.function_name()
  1. Accessing attributes and methods of an object:
    • object_name: The name of the object you want to access.
    • attribute_name: The name of the attribute you want to access from the object. This can be a variable associated with the object.
    • method_name(): The name of the method you want to call on the object. This can be a function associated with the object.
  2. Accessing attributes and functions within modules and packages:
    • module_name: The name of the module or package you want to access.
    • attribute_name: The name of the attribute you want to access from the module or package. This can be a variable defined in the module or package.
    • function_name(): The name of the function you want to call from the module or package.

Note: when using the dot operator, the left side of the dot should be an object or a module/package name, while the right side should be the attribute or method name you want to access or call.

Python dot operator example

Here’s an example that demonstrates the usage of the dot operator in Python:

# Define a class called Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is", self.name)


# Create an instance of the Person class
person = Person("Alice", 25)

# Accessing attributes using the dot operator
print(person.name) 
print(person.age)  

# Calling a method using the dot operator
person.say_hello()

Output:

Python dot operator

In this example, we define a class called Person with attributes name and age, and a method say_hello(). We create an instance of the Person class named person. Using the dot operator, we can access the attributes name and age using person.name and person.age, respectively. We also call the say_hello() method using person.say_hello().

Do comment if you have any doubts or suggestions on this Python operator 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 *