Python Fundamentals
eBook - ePub

Python Fundamentals

A practical guide for learning Python, complete with real-world projects for you to explore

Ryan Marvin, Mark Ng'ang'a, Amos Omondi

Compartir libro
  1. 324 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Python Fundamentals

A practical guide for learning Python, complete with real-world projects for you to explore

Ryan Marvin, Mark Ng'ang'a, Amos Omondi

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

With an interesting mix of theory and practicals, explore Python and its features, and progress from beginner to being skilled in this popular scripting language

Key Features

  • A comprehensive introduction to the world of Python programming
  • Paves an easy-to-follow path for you to navigate through concepts
  • Filled with over 90 practical exercises and activities to reinforce your learning

Book Description

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.

What you will learn

  • Use control statements
  • Manipulate primitive and non-primitive data structures
  • Use loops to iterate over objects or data for accurate results
  • Write encapsulated and succinct Python functions
  • Build Python classes using object-oriented programming
  • Manipulate files on the file system (open, read, write, and delete)

Who this book is for

Python Fundamentals is great for anyone who wants to start using Python to build anything from simple command-line programs to web applications. Prior knowledge of Python isn't required.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Python Fundamentals un PDF/ePUB en línea?
Sí, puedes acceder a Python Fundamentals de Ryan Marvin, Mark Ng'ang'a, Amos Omondi en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781789809947
Edición
1
Categoría
Programming

Object-Oriented Programming

Learning Objectives

By the end of this chapter, you will be able to:
  • Explain different OOP concepts and the importance of OOP
  • Instantiate a class
  • Describe how to define instance methods and pass arguments to them
  • Declare class attributes and class methods
  • Describe how to override methods
  • Implement multiple inheritance
This lesson introduces object-oriented programming as implemented in Python. We also cover classes and methods, as well as overriding methods and inheritance.

Introduction

A programming paradigm is a style of reasoning about programming problems. Problems, in general, can often be solved in multiple ways; for example, to calculate the sum of 2 and 3, you can use a calculator, you can use your fingers, you can use a tally mark, and so on. Similarly, in programming, you can solve problems in different ways.
At the beginning of this book, we mentioned that Python is multi-paradigm, as it supports solving problems in a functional, imperative, procedural, and object-oriented way. In this chapter, we will be diving into object-oriented programming in Python.

A First Look at OOP

Object-oriented Programming (OOP) is a programming paradigm based on the concept of objects. Objects can be thought of as capsules of properties and procedures/methods. In an interview with Rolling Stone magazine, Steve Jobs, co-founder of Apple, once explained OOP in the following way:
"Objects are like people. They're living, breathing things that have knowledge inside them about how to do things and have memory inside them so that they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction…"
Steve Jobs; Rolling Stone; June 16, 1994
An example of an object you can consider is a car. A car has multiple different attributes. It has a number of doors, a color, and a transmission type (for example, manual or automatic). A car, regardless of the type, also has specific behaviors: it can start, accelerate, decelerate, and change gears. Regardless of how these behaviors are implemented, the only thing we, the users of the car, care about, is that the aforementioned behaviors, such as acceleration, actually work.
In OOP, reasoning about data as objects allows us to abstract the actual code and think more about the attributes of the data and the operations around the data. OOP offers the following advantages:
  • It makes code reusable.
  • It makes it easier to design software as you can model it in terms of real-world objects.
  • It makes it easier to test, debug, and maintain.
  • The data is secure due to abstraction and data hiding.
With the benefits it confers, OOP is a powerful tool in a programmer's tool box.
In the next section, we'll be looking at how OOP is used in Python.

OOP in Python

Classes are a fundamental building block of object-oriented programming. They can be likened to blueprints for an object, as they define what properties and methods/behaviors an object should have.
For example, when building a house, you'd follow a blueprint that tells you things such as how many rooms the house has, where the rooms are positioned relative to one another, or how the plumbing and electrical circuitry is laid out. In OOP, this building blueprint would be the class, while the house would be the instance/object.
In the earlier lessons, we mentioned that everything in Python is an object. Every data type and data structure you've encountered thus far, from lists and strings to integers, functions, and others, are objects. This is why when we run the type function on any object, it will have the following output:
>>> type([1, 2, 3])
<class 'list'>
>>> type("foobar")
<class 'str'>
>>> type({"a": 1, "b": 2})
<class 'dict'>
>>> def func(): return True
...
>>> type(func)
<class 'function'>
>>>
You'll note that calling the type function on each object prints out that it is an instance of a specific class. Lists are instances of the list class, strings are instances of the str class, dictionaries are instances of the dict class, and so on and so forth.
Each class is a blueprint that defines what behaviors and attributes objects will contain and how they'll behave; for example, all of the lists that you create will have the lists.append() method, which allows you to add elements to the list.
Here, we are creating an instance of the list class and printing out the append and remove methods. It tells us that they are methods of the list object we've instantiated:
>>> l = [1, 2, 3, 4, 5] # create a list object
>>> print(l.append)
<built-in method append of list object at 0x10dd36a08>
>>> print(l.remove)
<built-in method remove of list object at 0x10dd36a08>
>>>

Note

In this chapter, we will use the terms instance and object synonymously.

Defining a Class in Python

In our example, we'll be creating the blueprint for a person. Compared to most languages, the syntax for defining a simple class is very minimal in Python.

Exercise 31: Creating a Class

In this exercise, we will create our first class, called Person. The steps are as follows:
  1. Declare the class using the Python keyword class, followed by the class name Person. In the block, we have the Python keyword pass, which is used as a placeholder for...

Índice