How to Declare a Class in Python
In Python, a class is declared using the class
keyword.
A class name is typically written in Pascal Case
, where each word starts with a capital letter
.
In Pascal Case
, multiple words are combined without spaces, and each word starts with a capital letter.
For example, total amount
becomes TotalAmount
, with spaces removed and the first letter of each word capitalized.
Basic Structure of a Class Declaration
The basic structure for declaring a class is as follows.
class ClassName:
# Definition of attributes and methods
...
After the class
keyword, the class name is followed by a colon (:
), and the body of the class includes its attributes and methods.
You can create an object
from the class by placing parentheses ()
after the class name.
test = ClassName()
The above code demonstrates how to create an object named test
using the ClassName
class.
If the class has a constructor method (__init__
) that accepts parameters, you need to pass arguments when creating an object.
class ClassName:
def __init__(self, arg1, arg2):
# Contents of the constructor method
...
test = ClassName(arg1, arg2)
As shown above, you must pass arg1
, arg2
that match the type and number of arguments defined in the constructor method __init__
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.