Skip to content

Creating Classes

  • Lesson
  • 3 min read
  • 2 of 7 in this chapter

Writing classes

In Python, to write the blueprint for a group of objects, or a class, we must follow a certain syntax…

Python
class Class_name:
	attribute1 = value1
	attribute2 = value2

Here, class_name should be replaced with the name of the class, and all the default attributes (or variable values) should be set below the class’s name, as shown.

Python
class Car:
	car_type = "sedan"
	year = 2001
	mileage = 30500

Here, I have created a Car class with three attributes set to default values: type, year, and mileage.

Object Installation

After you have created the blueprint for objects (i.e. the class), to actually create an object we must "instantiate" it (i.e. make an instance of it).

Python
object_name = class_name()

object_name should be replaced by the unique name you want to give to this particular object of the class. "class_name" should be the name of the class, obviously. Do note, the () are a must.

Python
mercE330 = Car()
print(mercE330)   

OUTPUT

Text
<__main__.Car object at 0x10529f250>

This output isn’t particularly appealing, I’ll admit. We’ll get to how to actually access attributes next!

Modifying and Accessing Object Attributes

To access an attribute of a specific object of a class, we use ./dot notation. Basically, object_name.attribute_name. So, to access the year of the car object we created earlier, do the following:

Python
print(mercE330.year)

OUTPUT

Text
2001

On top of accessing these attributes, you can also edit their values using . notation. Just use the assignment operator =.

Python
mercE330.year = 2005
print(mercE330.year)

OUTPUT

Text
2005

Object Methods/Functions

Aside from attributes, objects in python can also have their own functions that act on the data of the object. For example, with the car, we could have a function to drive, and add miles to mileage as we drive.

First, we’ll need to add the function (also called a method) to the class definition. In Python, the first argument of all object methods is the object itself, so we typically write self as a placeholder for the object itself.

Any other arguments are entered separated by a comma after the self.

Python
class Car:
    car_type = "sedan"
    year = 2001
    mileage = 30500
    def drive(self):
        self.mileage = self.mileage + 5

Performing Object Methods/Functions

To actually get the object to run its method, (the method will only run for this object, not all objects of the class) we must call the method, like any other function.

Python
print(mercE330.mileage)
mercE330.drive()
print(mercE330.mileage)

OUTPUT

Text
30500
30505

Voila! The drive method worked, and the object successfully changed its own attributes after its method was called. That’s the basics of object attributes and methods. Moving on to the initialization of objects!