How to Declare a Class in Python
In Python, a class is declared using the class
keyword.
Class names are typically written in Pascal Case
, where the name starts with a capital letter
.
Pascal Case
involves merging multiple words into one, capitalizing the first letter of each word.
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, write the class name followed by a colon (:
) to define the attributes and methods of the class.
A class created this way can be used to instantiate an object 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.