Python is an object-oriented programming language. What this means is that almost everything is an object. An object in Python is a collection of attributes that collectively describe a "thing". That "thing" can be anything you want: a book, an animal, a movie.

To create an object, we must first define a class.

Creating a Class

Creating a class is simply defining the blueprint that will be used by all subsequent objects. To define a class, use the class keyword, and define the data points inside.

PYTHON
class Person: name = "Barack Obama"

That's it, we've defined a class, called Person and it contains a property named name which is set to Barack Obama.

Now that we have our class defined, let's create a Barack Obama!

Creating an Object

To create a new object, simply reference the class you want to build the object out of. In this case, we'll use our previously defined Person class.

PYTHON
class Person: name = "Barack Obama" person = Person() print(person.name)
BASH
Barack Obama

Awesome, we created a new person and printed out the name by accessing the property directly. This is cool and all, but now let's make our classes useful.

Class Constructor

You can pass in parameters to the object creation process similar to how you can pass in parameters to functions. You do this by defining a constructor for your class that can initialize your new object using parameters that you pass in.

Let's allow the name of the person to be customizable by using the built-in __init__ function.

PYTHON
class Person: def __init__(self, name): self.name = name person = Person("Ash Ketchum") print(person.name)
BASH
Ash Ketchum

Since classes are just blueprints for objects, you can also create multiple objects using the same class:

PYTHON
class Person: def __init__(self, name): self.name = name person1 = Person("Ash Ketchum") person2 = Person("Brock Harrison") print(person1.name) print(person2.name)
BASH
Ash Ketchum Brock Harrison

You can also change an object's property directly:

PYTHON
class Person: def __init__(self, name): self.name = name person1 = Person("Ash Ketchum") print(person1.name) person1.name = "Misty Williams" print(person1.name)
BASH
Ash Ketchum Misty Williams

The self keyword is used to refer to the current object being created. Hence when the constructor is called (which happens automatically), it is setting the new object's properties using the parameters you passed in.

Object Methods

Strings and numbers aren't the only thing you can define in classes. Objects can also contain functions. Let's create one in our Person class.

PYTHON
class Person: def __init__(self, name): self.name = name def introduction(self): print("Hi, my name is " + self.name) person1 = Person("Ash Ketchum") person2 = Person("Brock Harrison") person1.introduction() person2.introduction()
BASH
Hi, my name is Ash Ketchum Hi, my name is Brock Harrison

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.