Dot Notation

Dot notation is how you access the members of an object.

When we want to access variables or methods in OOP, we have to use dot notation. This is because we could be working with many different object instances at one time, and if we didn’t specify which object we were referring to, python wouldn’t know which one to choose! For example, if you call bark(), you could be referring to the Fido dog we instantiated earlier, or other dog objects you’ve instantiated in another part of your code: Sam, Max, Gilbert…(Fido has many friends). To access a variable or method inside of a class, you use the following notation:

  • instance_name.class_attribute

  • instance_name.instance_attribute

  • instance_name.method(parameters of method)

>>> fido = Dog("Fido", 5, "black")
>>> fido.scientific_name
canis lupus familiaris
>>> fido.age
5
>>> fido.fur_color
black
>>> fido.bark()
woof woof!!

When we call fido.scientific_name, it's easy to figure out what gets returned. The scientific name of a dog is a class attribute, which means it is shared by all instances of a dog. Since we defined it in the class (Side note: Notice that this variable is not in the __init__ constructor) as the string "canis lupus familiaris", we simply return this string. Things get a little more complicated when we are referring to an object’s instance attributes.

When we call fido.age or fido.fur_color, we have to look at the keyword self. Earlier, we said that self allows us to refer to a particular instance of a class. In other words, when the code says self.age, self.name etc, self refers to the specific instance of the dog we passed into the function using dot notation. For example, when we call fido.age, we refer to self.age (in the constructor), and since self is fido, we return fido’s age.

Also notice that self is a parameter of every method in our class, such as bark(self). Even if self is a parameter in each method in the class, you don’t need an argument for it, because python refers to self as the instance from the left side of the dot (when the programmer invokes dot notation). Thus, you can also refer to an object’s attributes within a method! You can instead define the method bark as:

# self.name refers to whatever the passed in dog's name is. 
def bark(self):
    print(self.name + " says woof woof!!")
    
>>> fido.bark()
Fido says woof woof!!

Last updated