Python Lesson 17: Creating and using classes in Python

Python is an object oriented language. Learning to create objects is key to mastering Python. Classes define objects. 

  1. Create a basic class in Python
  2. Create an Object from a Class
  3. Assign values to Class Properties in Python
  4. Create a Class with a Method in Python

1) Create a basic class in Python

To create a class in Python use the “class” keyword. Classes has properties and methods. This basic class will have just one property.

#Class with a Property
class Car():
    model = "BMW"

2) Create an Object from a Class

To create an object from the class set a variable to a class name

#Instantiate a Object from a class
mycar = Car()
print(mycar.model)
#Instantiate a Object from a class
mycar = Car()
print(mycar.model)
Notebook Output

3) Assign values to Class Properties in Python

To assign values to class attributes use the __init__() function

class Car():
    
    def __init__(self,make,model,year,color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        
mycar = Car("BMW","X5",2018,"Black")
Notebook Output

4) Create a Class with a Method in Python

Class methods are nested functions that include self as a parameter.

class Car():
    
    def __init__(self,make,model,year,color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color
        
    def outputvalues(self):
        #returns all parameter values as a tuple
        vals = (self.make, self.model, self.year, self.color)
        return vals
        
mycar = Car("BMW","X5",2018,"Black")
print(mycar.outputvalues())
Notebook Output

Recommended Books