Python Introduction | Using Classes | Creating Classes

Let us create and use a class. The following example moves the earlier process of displaying a message with a name into a Member class.

class Member: 
    name = "" 
   
    def showMsg(self): 
        print("Hello, " + self.name + ". How are you?")

The member variable name stores a name. The showMsg method displays a message.

The source code introduces self, which appears as an argument of showMsg. It is not an ordinary argument.

Inside the method, the expression self.name refers to a member variable.

self is a special value that represents the current instance. It does not represent the class itself.

Instances and self

A class is like a blueprint. You do not usually operate on the blueprint directly. Instead, create an instance from the class and operate on that instance.

If you used a class directly, you could not independently store data for both "Taro" and "Hanako" in the same name variable. Instead, create separate Member instances and assign a name to each one.

self refers to the current instance. When a method needs a member variable stored in that instance, use a qualified name such as self.name.

Python methods receive the instance as their first argument. Access its member variables and methods by writing a dot after self.

self.variable

For example, use self.name to access the name member variable.