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

Class Versus Instance Methods


In this section, we will take a brief look at instance methods and cover class methods in detail.

Exercise 40: Creating Instance Methods

In this exercise, we will implement the navigate() and clear_history() methods for the WebBrowser class we defined in the previous section:

  1. Add the navigate() method to the WebBrowser class:

    class WebBrowser:
        def __init__(self, page):
            self.history = [page]
            self.current_page = page
            self.is_incognito = False
    
        def navigate(self, new_page):
            self.current_page = new_page
            if not self.is_incognito:
                self.history.append(new_page)

    Any call to navigate will the set the browser's current page to the new_page argument and then add it to the history if we're not in incognito mode (incognito mode in browsers prevents browsing history from being recorded).

  2. Calling navigate() on an instance should change current_page:

    >>> vivaldi = WebBrowser("gocampaign.org")
    >>> vivaldi...