Class


A class is a blueprint for an object. It defines the attributes and methods that an object will have.


How to define a class


Here’s how to design a class:

class Beam:  # the "class" keyword tells Python we are creating a class name "Beam"
    def __init__(self, length, width, height):  # this is a constructor
        self.length = length  # these are attributes
        self.width = width
        self.height = height

    def calculate_volume(self):  # this is a method
        """Calculate the volume of the beam"""  # this is a docstring, it is used to document the method
        volume = self.length * self.width * self.height
        return volume


➔➔ Note that class names in Python are written in 🐪CamelCase🐪 and not 🐍snake_case🐍 (e.g. BeamSprouce, BeamGlulam, etc.)


How to create (or instantiate) a class


Once you designed your class, you can create objects of that class. This is called instantiating a class. To do this, you simply write the name of the class followed by the values you want to feed into the constructor and assign it to a new variable .

# class instatiation
beam = Beam(10, 20, 30)

# calling a method
volume = beam.calculate_volume()
print(volume)       # 6000

# accessing attributes
print(beam.length)  # 10
print(beam.width)   # 20
print(beam.height)  # 30


🛠 Exercise


01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍