Course Overview and Lesson Goal

Hello, Explorer! Today, we're delving into the realm of Python's Object-Oriented Programming (OOP), focusing on class attributes and methods. Our goal is to grasp these concepts using clear, practical examples. Let's get started!

Introduction to Class Attributes

Class attributes are properties of class instances. For instance, a Spaceship class could include attributes such as color, max speed, and fuel capacity. These are defined within the class block, as shown below:

class Spaceship:
    color = "white"
    max_speed = 10000
    fuel_capacity = 20000

These attributes can be accessed through a class instance, like so:

enterprise = Spaceship()
print(enterprise.color)  # prints: white
print(enterprise.max_speed)  # prints: 10000
Methods in Action

Class methods define a class's behavior. For example, a spaceship can fly. Methods are essentially functions within a class. The fly method below enables an instance of the Spaceship class to fly:

class Spaceship:
    color = "white"
    fuel_capacity = 20000

    def fly(self, speed):
        return f"The {self.color} spaceship is flying! Speed = {speed}, fuel_capacity = {self.fuel_capacity}"

Note, that when referring to class attributes inside the class, you should always use the self keyword that's always provided as a first parameter in every method of the class, similarly to how we used self.color, and self.fuel_capacity in the example above. At the same time, the provided parameter speed is just used as is, as it's not a class attribute but an external parameter.

This fly method can be invoked in the following manner:

enterprise = Spaceship()
print(enterprise.fly(10000))  # prints: The white spaceship is flying! Speed = 10000, fuel_capacity = 20000
Interacting with Class Attributes and Methods

Attributes and methods can be accessed and implemented through class instances. The attributes of a class can be set, and its methods can be called, as demonstrated below:

enterprise = Spaceship()
enterprise.color = "blue"  # setting an attribute
enterprise.fly()  # calling a method
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal