× Lesson 1 Lesson 2 Lesson 3 Lesson 4 Lesson 5 Lesson 6 Lesson 7 Lesson 8 Lesson 9 Lesson 10 Lesson 11 Lesson 12 Lesson 13 Lesson 14 Lesson 15 Lesson 16 Lesson 17 Lesson 18 Lesson 19 Lesson 20 Lesson 21 Lesson 22 Lesson 23 Lesson 24 Lesson 25 Mini Lesson 1 Mini Lesson 2 Mini Lesson 3 Mini Lesson 4 Mini Lesson 5


Lesson 12 - Classes

Objects are used to create and hold functions and variables that are unique to that specific object. An example of an object is a specific breed of dog that has assigned attributes, variables and values for that dog such as the color of the fur, the breed of the dog, etc, and methods, which are basically functions in an object such as a method for the dog to bark and for it to wag its tail

Classes are used to create an instance of the class, which are objects. So, carrying on with the dog example, the class could be called Dog, and it is has attributes that are set equal to the values that you pass whenever you create a new Dog object.

The basic syntax for creating a class is has the following, using the dog example:

class Dog(object):

def __init__(self, breed, fur):

self.breed = breed

self.fur = fur

def bark(self):

print('Woof woof')

Make sure to always have self as an argument for everything, such as the self.__init__(self) and def bark(self). For the self.__init__ method make sure to always set self.(name of argument) equal to (name of argument). The only exception to this, for now, is if you want to keep the variable's value constant no matter which instance of the class, which in that case you would simply do self.(name of argument) equal to what ever value you want.

The syntax for creating a specific dog object using the Dog class is as the following, and I created an instance of the Dog class called Sam, which is a Chihuahua and has black fur. I also called the bark() method:

Can you guess how to do print out the attributes of a dog object? Click to reveal to see if you are correct!

I challenge you now to make your own class, which can be pretty much whatever you want, such as cars, birds, phones, etc, with attributes such as its size, gender, brand, and have a method such as the Dog's bark method, and create an instance of that class and run the method(s) for that object. Once you are done, move on to the next lesson.