Class Naming Conventions

Python has a set of rules and conventions that we use when naming our classes, methods, and attributes. These conventions are important because they ensure consistency in the code you write, making it easier to read and understand. It's also a professional best practice to adhere to these conventions.

Class Names

In Python, class names follow the CapWords convention, also known as PascalCase. In this style, the first letter of each word is capitalized and there are no underscores (_) between words:
class MyClass:  # Class name starts with a capital letter
    pass        # We use "pass" when we don't want the class to do anything
The term PascalCase originated from the Pascal programming language, attributing to its case convention. CapWords is the term used in Python's official style guide (PEP 8), and it's essentially the same as PascalCase.

Method Names

Method names should be all lowercase, with words separated by underscores as necessary to improve readability. This is also known as snake_case. Here's an example:
class MyClass:
    def my_method(self):  # Method name is all lowercase
        pass              # Where words are separated by underscores

Attribute Names

Attribute names follow the same convention as method names, they should be all lowercase, with words separated by underscores as necessary to improve readability.
class MyClass:
    def __init__(self):
        self.my_attribute = 'some value'  # Attribute name is all lowercase, 
                                          # words separated by underscores
In the above code, we've defined an attribute my_attribute inside the __init__ method. The __init__ method is a special method in Python classes that is automatically called when a new instance of the class is created.

Let's look at a full example of a class, its methods, and attributes:
class MyCar:                              # class name uses CapWords
    def __init__(self):
        self.car_model = 'Tesla Model 3'  # attribute name uses snake_case

    def start_engine(self):               # method name uses snake_case
        print('Engine started!')
While Python does not strictly enforce these naming conventions, adhering to them makes your code more professional, readable, and consistent. Therefore, it is considered good practice in the Python community.
To check your solution you need to sign in
Sign in to continue