Declaring a Class in Python
In this lesson, you will learn about declaring a class.
Declaration
In Python, we define classes in the following way:
The class keyword tells the compiler that we are creating our custom class, and this is followed by the class name and : sign.
All the properties and methods of the class will be defined within the class scope.
Naming Rules
The following rules must be adhered to when naming classes:
- Must start with a letter or underscore.
- Should only be comprised of numbers, letters or underscores.
Creating a Class Object
The name of the class, MyClass, will be used to instantiate an object of the class in our main program. We can create an object of a class by simply using the name of the class followed by a pair of parenthesis. It looks similar to calling a function, but Python can distinguish between the two and creates a new object of the corresponding class. An example of this is given below:
Well done! You have created your first object-oriented program in Python. Printing this object, obj, will show the memory address at which this object is stored.
This is just a basic implementation of a Python class and does not serve any purpose as it does not contain any property or method.
In the next few lessons, we will learn the implmentation of Python classes in detail.