Book Image

Python Fundamentals

By : Ryan Marvin, Mark Ng’ang’a, Amos Omondi
Book Image

Python Fundamentals

By: Ryan Marvin, Mark Ng’ang’a, Amos Omondi

Overview of this book

<p>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.</p> <p>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.</p> <p>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.</p>
Table of Contents (12 chapters)
Python Fundamentals
Preface

Chapter 7: Object-Oriented Programming


Activity 28: Defining a Class and Objects

Solution:

This is the MobilePhone class definition:

class MobilePhone:
    def __init__(self, display_size, ram, os):
        self.display_size = display_size
        self.ram = ram
        self.os = os

The solution can also be found in the code files for this chapter in the file named mobile_phone1.py.

Activity 29: Defining Methods in a Class

Solution:

import math


class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

    def circumference(self):
        return 2 * math.pi * self.radius

    def change_radius(self, new_radius):
        self.radius = new_radius


circle = Circle(7)

while True:
    radius = float(input("Circle radius: "))
    circle.change_radius(radius)
    print("Area:", circle.area())
    print("Circumference:", circle.circumference())

The solution can also be found in the code files for this chapter in the file named circle.py.

Activity 30: Creating Class Attributes

Solution:

class Elevator:
    occupancy_limit = 8

    def __init__(self, occupants):
        if occupants > self.occupancy_limit:
            print("The maximum occupancy limit has been exceeded."
                  f" {occupants - self.occupancy_limit} occupants must exit the elevator.")
        self.occupants = occupants


elevator1 = Elevator(6)
print("Elevator 1 occupants:", elevator1.occupants)
elevator2 = Elevator(10)
print("Elevator 2 occupants:", elevator2.occupants)

The solution can also be found in the code files for this book in the file named elevator.py.

Activity 31: Creating Class Methods and Using Information Hiding

Solution:

class MusicPlayer:
    firmware_version = 1.0

    def __init__(self):
        self.__tracks = ["Moonage Daydream", "Starman", "Life on Mars?"]
        self.current_track = None

    def play(self):
        self.current_track = self.__tracks[0]

    def list_tracks(self):
        return self.__tracks

    @classmethod
    def update_firmware(cls, new_version):
        if new_version > cls.firmware_version:
            cls.firmware_version = new_version

player = MusicPlayer()
print("Tracks currently on device:", player.list_tracks())

MusicPlayer.update_firmware(2.0)
print("Updated player firmware version to", player.firmware_version)
player.play()
print("Currently playing", f"'{player.current_track}'")

The solution can also be found in the code files for this course in the file named musicplayer.py.

Activity 32: Overriding Methods

Solution:

class Cat:
    def __init__(self, mass, lifespan, speed):
        self.mass_in_kg = mass
        self.lifespan_in_years = lifespan
        self.speed_in_kph = speed

    def vocalize(self):
        print("Chuff")

    def __str__(self):
        return f"The {type(self).__name__.lower()} "\
            f"weighs {self.mass_in_kg}kg,"\
            f" has a lifespan of {self.lifespan_in_years} years and "\
            f"can run at a maximum speed of {self.speed_in_kph}kph."


class Tiger(Cat):
    def __init__(self, mass, lifespan, speed):
        super().__init__(mass, lifespan, speed)
        self.coat_pattern = "striped"
    def __str__(self):
        facts = super().__str__()
        facts = f"{facts} It also has a {self.coat_pattern} coat."
        return facts

tiger = Tiger(310, 26, 65)
print(tiger)

The solution for this activity can also be found in the tiger.py file in the attached code files for this chapter.

Activity 33: Practicing Multiple Inheritance

Solution:

class MobilePhone:
    def __init__(self, memory):
        self.memory = memory


class Camera:
    def take_picture(self):
        print("Say cheese!")

class CameraPhone(MobilePhone, Camera):
    pass


cameraphone = CameraPhone("200KB")
cameraphone.take_picture()
print(cameraphone.memory)

The solution for this activity can also be found in the cameraphone.py file in the attached code files for this chapter.