18 June 2018

A Beginner’s Guide to Python Object-Oriented Programming


beginner-python-programming

Python is used in everything from the Raspberry Pi to machine learning. If you want to work on any large project however, you’ll need to know how Python works with object-oriented programming (OOP). This article will cover the very basics you need to know.

If you’re not actually into programming, why not take a look at these best Monty Python sketches instead? They did inspire the language, after all!

Wait, Python’s Not a Real Language?

Let’s get one thing clear: Python IS a real programming language, it’s popular, and it’s rapidly growing. Just because it reads like pseudocode and you can code Minecraft on the Pi with it, that doesn’t mean you should discount it as a lesser language.

OOP is the cornerstone of modern software development, and Python is more than capable of keeping up. It may do one or two things differently than other mainstream languages, but don’t let that put you off.

object-oriented programming guide for python

This tutorial will assume a basic knowledge of Python, but we’ll cover all the complex stuff along the way. If you’re new to Python, why not look at these tricks to learning a new programming language, or what about a simple project such as reading and writing to Google Sheets with Python?

Python Prerequisites and Setup

Before getting started, you may wish to get your Python development environment setup. We’ll be using Python 3.6.5, and while you can use older versions, you’ll have less problems following along if you’re using a fairly new version.

You’ll want to create a virtual environment if you don’t have one already, and install PIP for Python if that’s not installed (it comes with most modern installs of Python though). Once you got those setup, you’ll be good to go. Let’s get started!

The Basics of Python: Classes

A class is the basic building block of OOP. A class is like a plan or blueprint. They define characteristics of an object. If you have a car class, for example, it may state that there are four wheels, at least one seat, and an engine.

Here’s how to make a class in Python:

class Vehicle:
  """ This class defines vehicles. """
  pass

Simple right? There’s a few things going on here. Notice the comment at the top of the class. This is a special comment called a docstring. It should explain a bit about your code. By using the triple quotes (“””), you’re telling Python that this is a docstring.

The pass keyword tells Python do to nothing. It’s a special word, and you can think of it like a todo. It will make your code run, but it doesn’t actually do anything.

If you run this code, you’ll see that nothing happens. You need to instantiate you class. This effectively means to go and build an object based on the plan defined in the class. You can create as many copies as you like, each with different properties. Here’s how you do that:

red_car = Vehicle()

If you run this again, you’ll see that nothing happens. The code is working correctly, but you’ve not told it to do anything noticeable. The Vehicle class defines blueprints for a vehicle, and this latest line creates a vehicle object, and gives it a name of red_car.

It’s possible to make as many objects as you like:

red_car = Vehicle()
green_car = Vehicle()
blue_car = Vehicle()

Let’s add some more code. Add a method called __init__ to the Vehicle class:

class Vehicle:
  """ This class defines vehicles. """

  def __init__(self, color='plain'):
  """ Setup some custom car properties """
  print('New car made!')
  self.color = color

red_car = Vehicle()
green_car = Vehicle()
blue_car = Vehicle()

Pay special attention to this __init__ method. It must begin and end with two underscores. This is a special method in Python. It gets called automatically when you create a new object. Running this code will show the words “New car made!” three times.

object-oriented programming guide for python

Finally, __init__ takes a custom argument called color. The equals sign and string immediately following tell Python to set the color to “plain” if not specified. You can modify your instances to setup your car color at creation:

red_car = Vehicle(color='red')
green_car = Vehicle(color='green')
blue_car = Vehicle(color='blue')

If you print the car color, you’ll see that each instance has a different color, even though all three were made to the same specification (the class). Python allows you to access nearly any variable or object—not many other languages allow you to do this:

print(red_car.color)
print(green_car.color)
print(blue_car.color)

object-oriented programming guide for python

This works because you assigned color to self.color. Self is another special keyword in Python, and it refers to each specific instance of a class. Whenever you use self, you can set or access data unique to that instance. The red car has a color of red, for example.

Modify your __init__ method to store the car noise in a variable:

self.noise = 'Vroooom'

To print the car noise, you could just access the noise variable, like you did with color, but this isn’t the best idea. What if, when you drive a car, you want some other code to run at the same time, maybe code that you haven’t written yet? Or what if you want to change how a car drives in the future? By creating a function (also known as a method), you can tightly control how things work. Add this below your __init__ method:

def drive(self):
  print(self.noise)

You can call this method quite simply:

red_car.drive()

object-oriented programming guide for python

Whenever you call the drive method, Python will print the sound. You can expand this to perform all manor of tasks, but leave it as is for now.

Well done! By now you should have a firm grip on the basics. You should be able to create and use your own classes, each with their own unique abilities and functions.

What About Private Variables in Python?

Private objects are very common in most other languages. They are simply variables or functions that cannot be accessed outside the class. They may be code that requires special conditions to be met before use, or simply designed for internal use only. Whatever the reason, instances cannot access private members… unless you’re coding in Python.

Python does not have private members. Instead, Python relies on an honor system: “We are all consenting adults.” Python programmers understand that you may want to tinker with the sensitive internals of a class, and that’s okay, so nothing should ever be truly inaccessible.

However, Python does have an accepted convention for marking certain variables as “private” in the sense of “This variable is for internal use and you probably don’t need to touch it.” The convention is to prefix variable names with an underscore:

_some_secret_variable = 42

This acts as a warning to other programmers. Python won’t stop you accessing this, but the underscore advices you that this was not designed to be used this way, and you should continue at your own risk.

It’s sometimes the Python way to tinker with hidden stuff, but you run the risk that things may not work properly.

Understanding Inheritance in Python

Inheritance is another way to reduce duplication and reuse code. Thinking of a parent and child relationship, inheritance allows the child to share common code with the parent. Let’s implement an electric car, which inherits from the parent.

Add this code below your Vehicle class:

class ElectricCar(Vehicle):
  """ Electric vehicle class. """
  def charge(self):
  print('Zzz')

electric_car = ElectricCar()
electric_car.charge()
electric_car.noise = 'Whoosh'
electric_car.drive()

object-oriented programming guide for python

After the ElectricCar is defined, the Vehicle class is specified inside two brackets. This tells Python that ElectricCar is a child of Vehicle. This gives it access to all the data and methods provided in Vehicle.

The electric car has its own special methods. It can charge (something that other vehicles cannot do). By changing the car noise, and then driving, you can see that the electric car makes a different sound, and you didn’t have to define the drive method. This is because drive is inherited from the parent.

Expand Your Python Knowledge Even Further

These examples have shown just how easy OOP can be in Python. We’ve only just covered the very basics, but once you’ve got those down, the rest is easy.

If you’re looking to continue learning Python, or perhaps put these OOP skills into practice, why not have a look at arrays and lists in Python, or what about getting Python and JavaScript to communicate?

If all of this has left you wanting more, then don’t forget to check out these best websites to learn Python.

Read the full article: A Beginner’s Guide to Python Object-Oriented Programming


Read Full Article

No comments:

Post a Comment