Book Image

Python Fundamentals

By : Ryan Marvin, Mark Nganga, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Nganga, Amos Omondi

Overview of this book

After a brief history of Python and key differences between Python 2 and Python 3, you'll understand how Python has been used in applications such as YouTube and Google App Engine. As you work with the language, you'll learn about control statements, delve into controlling program flow and gradually work on more structured programs via functions. As you settle into the Python ecosystem, you'll learn about data structures and study ways to correctly store and represent information. By working through specific examples, you'll learn how Python implements object-oriented programming (OOP) concepts of abstraction, encapsulation of data, inheritance, and polymorphism. You'll be given an overview of how imports, modules, and packages work in Python, how you can handle errors to prevent apps from crashing, as well as file manipulation. By the end of this book, you'll have built up an impressive portfolio of projects and armed yourself with the skills you need to tackle Python projects in the real world.
Table of Contents (12 chapters)
Python Fundamentals
Preface

Methods in a Class


In this topic, we will look at class methods in detail.

Defining Methods in a Class

So far, we've seen how to add attributes to an object. As we mentioned earlier, objects are also comprised of behaviors known as methods. Now we will take a look at how to add our own methods to classes.

Exercise 34: Creating a Method for our Class

We'll rewrite our original Person class to include a speak() method. The steps are as follows:

  1. Create a speak() method in our Person class, as follows:

    class Person:
        def __init__(self, name, age, height_in_cm):
            self.name = name
            self.age = age
            self.height_in_cm = height_in_cm
        
        def speak(self):
            print("Hello!")

    The syntax for defining an instance method is familiar. We pass the argument self which, as in the __init__ method, refers to the current object at hand. Passing self will allow us to get or set the object's attributes inside our function. It is always the first argument of an instance method.

  2. Instantiate...