Python Inheritance



 Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.


Parent class is the class being inherited from, also called base class.


Child class is the class that inherits from another class, also called derived class.


Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:


Example

Create a class named Person, with firstname and lastname properties, and a printname method:


class Person:

  def __init__(self, fname, lname):

    self.firstname = fname

    self.lastname = lname


  def printname(self):

    print(self.firstname, self.lastname)


#Use the Person class to create an object, and then execute the printname method:


x = Person("John", "Doe")

x.printname()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:


Example

Create a class named Student, which will inherit the properties and methods from the Person class:


class Student(Person):

  pass

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.


Now the Student class has the same properties and methods as the Person class.


Example

Use the Student class to create an object, and then execute the printname method:


x = Student("Mike", "Olsen")

x.printname()

Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its parent.


We want to add the __init__() function to the child class (instead of the pass keyword).


Note: The __init__() function is called automatically every time the class is being used to create a new object.


Example

Add the __init__() function to the Student class:


class Student(Person):

  def __init__(self, fname, lname):

    #add properties etc.

When you add the __init__() function, the child class will no longer inherit the parent's __init__() function.


Note: The child's __init__() function overrides the inheritance of the parent's __init__() function.


To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__() function:


Example

class Student(Person):

  def __init__(self, fname, lname):

    Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function.


Use the super() Function

Python also has a super() function that will make the child class inherit all the methods and properties from its parent:


Example

class Student(Person):

  def __init__(self, fname, lname):

    super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.


Add Properties

Example

Add a property called graduationyear to the Student class:


class Student(Person):

  def __init__(self, fname, lname):

    super().__init__(fname, lname)

    self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the __init__() function:


Example

Add a year parameter, and pass the correct year when creating objects:


class Student(Person):

  def __init__(self, fname, lname, year):

    super().__init__(fname, lname)

    self.graduationyear = year


x = Student("Mike", "Olsen", 2019)

Add Methods

Example

Add a method called welcome to the Student class:


class Student(Person):

  def __init__(self, fname, lname, year):

    super().__init__(fname, lname)

    self.graduationyear = year


  def welcome(self):

    print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Python Iterators

 


Python Iterators

An iterator is an object that contains a countable number of values.


An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.


Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().


Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.


All these objects have a iter() method which is used to get an iterator:

Example

Return an iterator from a tuple, and print each value:


mytuple = ("apple", "banana", "cherry")

myit = iter(mytuple)


print(next(myit))

print(next(myit))

print(next(myit))

Even strings are iterable objects, and can return an iterator:


Example

Strings are also iterable objects, containing a sequence of characters:


mystr = "banana"

myit = iter(mystr)


print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

Looping Through an Iterator

We can also use a for loop to iterate through an iterable object:


Example

Iterate the values of a tuple:


mytuple = ("apple", "banana", "cherry")


for x in mytuple:

  print(x)

Example

Iterate the characters of a string:


mystr = "banana"


for x in mystr:

  print(x)

The for loop actually creates an iterator object and executes the next() method for each loop.


Create an Iterator

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.


As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created.


The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.


The __next__() method also allows you to do operations, and must return the next item in the sequence.


Example

Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):


class MyNumbers:

  def __iter__(self):

    self.a = 1

    return self


  def __next__(self):

    x = self.a

    self.a += 1

    return x


myclass = MyNumbers()

myiter = iter(myclass)


print(next(myiter))

print(next(myiter))

print(next(myiter))

print(next(myiter))

print(next(myiter))

StopIteration

The example above would continue forever if you had enough next() statements, or if it was used in a for loop.


To prevent the iteration to go on forever, we can use the StopIteration statement.


In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:


Example

Stop after 20 iterations:


class MyNumbers:

  def __iter__(self):

    self.a = 1

    return self


  def __next__(self):

    if self.a <= 20:

      x = self.a

      self.a += 1

      return x

    else:

      raise StopIteration


myclass = MyNumbers()

myiter = iter(myclass)


for x in myiter:

  print(x)


Python Scope

 


A variable is only available from inside the region it is created. This is called scope.


Local Scope

A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.


Example

A variable created inside a function is available inside that function:


def myfunc():

  x = 300

  print(x)


myfunc()

Function Inside Function

As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function:


Example

The local variable can be accessed from a function within the function:


def myfunc():

  x = 300

  def myinnerfunc():

    print(x)

  myinnerfunc()


myfunc()

Global Scope

A variable created in the main body of the Python code is a global variable and belongs to the global scope.


Global variables are available from within any scope, global and local.


Example

A variable created outside of a function is global and can be used by anyone:


x = 300


def myfunc():

  print(x)


myfunc()


print(x)

Naming Variables

If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function):


Example

The function will print the local x, and then the code will print the global x:


x = 300


def myfunc():

  x = 200

  print(x)


myfunc()


print(x)

Global Keyword

If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.


The global keyword makes the variable global.


Example

If you use the global keyword, the variable belongs to the global scope:


def myfunc():

  global x

  x = 300


myfunc()


print(x)

Also, use the global keyword if you want to make a change to a global variable inside a function.


Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:


x = 300


def myfunc():

  global x

  x = 200


myfunc()


print(x)


Python Modules

 


What is a Module?

Consider a module to be the same as a code library.


A file containing a set of functions you want to include in your application.


Create a Module

To create a module just save the code you want in a file with the file extension .py:


Example

Save this code in a file named mymodule.py


def greeting(name):

  print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:


Example

Import the module named mymodule, and call the greeting function:


import mymodule


mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.


Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):


Example

Save this code in the file mymodule.py


person1 = {

  "name": "John",

  "age": 36,

  "country": "Norway"

}

Example

Import the module named mymodule, and access the person1 dictionary:


import mymodule


a = mymodule.person1["age"]

print(a)

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py


Re-naming a Module

You can create an alias when you import a module, by using the as keyword:


Example

Create an alias for mymodule called mx:


import mymodule as mx


a = mx.person1["age"]

print(a)

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.


Example

Import and use the platform module:


import platform


x = platform.system()

print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:


Example

List all the defined names belonging to the platform module:


import platform


x = dir(platform)

print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.


Import From Module

You can choose to import only parts from a module, by using the from keyword.


Example

The module named mymodule has one function and one dictionary:


def greeting(name):

  print("Hello, " + name)


person1 = {

  "name": "John",

  "age": 36,

  "country": "Norway"

}

Example

Import only the person1 dictionary from the module:


from mymodule import person1


print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"]

Python Datetime

 


 Python Dates

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

Example

Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()

print(x)

Date Output

When we execute the code from the example above the result will be:

2021-09-24 02:04:28.441207

The date contains year, month, day, hour, minute, second, and microsecond.

The datetime module has many methods to return information about the date object.

Here are a few examples, you will learn more about them later in this chapter:

Example

Return the year and name of weekday:

import datetime

x = datetime.datetime.now()

print(x.year)

print(x.strftime("%A"))

Creating Date Objects

To create a date, we can use the datetime() class (constructor) of the datetime module.

The datetime() class requires three parameters to create a date: year, month, day.

Example

Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).


The strftime() Method

The datetime object has a method for formatting date objects into readable strings.


The method is called strftime(), and takes one parameter, format, to specify the format of the returned string:


Example

Display the name of the month:


import datetime


x = datetime.datetime(2018, 6, 1)


print(x.strftime("%B"))

A reference of all the legal format codes:


Directive Description Example

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

%p AM/PM PM

%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST

%j Day number of year 001-366 365

%U Week number of year, Sunday as the first day of week, 00-53 52

%W Week number of year, Monday as the first day of week, 00-53 52

%c Local version of date and time Mon Dec 31 17:41:00 2018

%C Century 20

%x Local version of date 12/31/18

%X Local version of time 17:41:00

%% A % character %

%G ISO 8601 year 2018

%u ISO 8601 weekday (1-7) 1

%V ISO 8601 weeknumber (01-53) 01 

Python Math

 


Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

Built-in Math Functions

The min() and max() functions can be used to find the lowest or highest value in an iterable:

Example

x = min(5, 10, 25)

y = max(5, 10, 25)

print(x)

print(y)

The abs() function returns the absolute (positive) value of the specified number:

Example

x = abs(-7.25)

print(x)

The pow(x, y) function returns the value of x to the power of y (xy).

Example

Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)

The Math Module

Python has also a built-in module called math, which extends the list of mathematical functions.

To use it, you must import the math module:

import math

When you have imported the math module, you can start using methods and constants of the module.

The math.sqrt() method for example, returns the square root of a number:

Example

import math

x = math.sqrt(64)

print(x)

The math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer, and returns the result:

Example

import math

x = math.ceil(1.4)

y = math.floor(1.4)

print(x) # returns 2

print(y) # returns 1

The math.pi constant, returns the value of PI (3.14...):

Example

import math

x = math.pi

print(x)

Complete Math Module Reference

In our Math Module Reference you will find a complete reference of all methods and constants that belongs to the Math module.

Python JSON

 


JSON is a syntax for storing and exchanging data.


JSON is text, written with JavaScript object notation.


JSON in Python

Python has a built-in package called json, which can be used to work with JSON data.


Example

Import the json module:


import json

Parse JSON - Convert from JSON to Python

If you have a JSON string, you can parse it by using the json.loads() method.


The result will be a Python dictionary.


Example

Convert from JSON to Python:


import json


# some JSON:

x =  '{ "name":"John", "age":30, "city":"New York"}'


# parse x:

y = json.loads(x)


# the result is a Python dictionary:

print(y["age"])

Convert from Python to JSON

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.


Example

Convert from Python to JSON:


import json


# a Python object (dict):

x = {

  "name": "John",

  "age": 30,

  "city": "New York"

}


# convert into JSON:

y = json.dumps(x)


# the result is a JSON string:

print(y)

You can convert Python objects of the following types, into JSON strings:


dict

list

tuple

string

int

float

True

False

None

Example

Convert Python objects into JSON strings, and print the values:


import json


print(json.dumps({"name": "John", "age": 30}))

print(json.dumps(["apple", "bananas"]))

print(json.dumps(("apple", "bananas")))

print(json.dumps("hello"))

print(json.dumps(42))

print(json.dumps(31.76))

print(json.dumps(True))

print(json.dumps(False))

print(json.dumps(None))

When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:


Python JSON

dict Object

list Array

tuple Array

str String

int Number

float Number

True true

False false

None null

Example

Convert a Python object containing all the legal data types:


import json


x = {

  "name": "John",

  "age": 30,

  "married": True,

  "divorced": False,

  "children": ("Ann","Billy"),

  "pets": None,

  "cars": [

    {"model": "BMW 230", "mpg": 27.5},

    {"model": "Ford Edge", "mpg": 24.1}

  ]

}


print(json.dumps(x))

Format the Result

The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.


The json.dumps() method has parameters to make it easier to read the result:


Example

Use the indent parameter to define the numbers of indents:


json.dumps(x, indent=4)

You can also define the separators, default value is (", ", ": "), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:


Example

Use the separators parameter to change the default separator:


json.dumps(x, indent=4, separators=(". ", " = "))

Order the Result

The json.dumps() method has parameters to order the keys in the result:


Example

Use the sort_keys parameter to specify if the result should be sorted or not:


json.dumps(x, indent=4, sort_keys=True)


Python RegEx



A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.


RegEx can be used to check if a string contains the specified search pattern.


RegEx Module

Python has a built-in package called re, which can be used to work with Regular Expressions.


Import the re module:


import re

RegEx in Python

When you have imported the re module, you can start using regular expressions:


Example

Search the string to see if it starts with "The" and ends with "Spain":


import re


txt = "The rain in Spain"

x = re.search("^The.*Spain$", txt)

RegEx Functions

The re module offers a set of functions that allows us to search a string for a match:


Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

Metacharacters

Metacharacters are characters with a special meaning:


Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special characters) "\d"

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "world$"

* Zero or more occurrences "aix*"

+ One or more occurrences "aix+"

{} Exactly the specified number of occurrences "al{2}"

| Either or "falls|stays"

() Capture and group  

Special Sequences

A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:


Character Description Example

\A Returns a match if the specified characters are at the beginning of the string "\AThe"

\b Returns a match where the specified characters are at the beginning or at the end of a word

(the "r" in the beginning is making sure that the string is being treated as a "raw string") r"\bain"

r"ain\b"

\B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word

(the "r" in the beginning is making sure that the string is being treated as a "raw string") r"\Bain"

r"ain\B"

\d Returns a match where the string contains digits (numbers from 0-9) "\d"

\D Returns a match where the string DOES NOT contain digits "\D"

\s Returns a match where the string contains a white space character "\s"

\S Returns a match where the string DOES NOT contain a white space character "\S"

\w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w"

\W Returns a match where the string DOES NOT contain any word characters "\W"

\Z Returns a match if the specified characters are at the end of the string "Spain\Z"

Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:


Set Description

[arn] Returns a match where one of the specified characters (a, r, or n) are present

[a-n] Returns a match for any lower case character, alphabetically between a and n

[^arn] Returns a match for any character EXCEPT a, r, and n

[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present

[0-9] Returns a match for any digit between 0 and 9

[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59

[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string

 

The findall() Function

The findall() function returns a list containing all matches.


Example

Print a list of all matches:


import re


txt = "The rain in Spain"

x = re.findall("ai", txt)

print(x)

The list contains the matches in the order they are found.


If no matches are found, an empty list is returned:


Example

Return an empty list if no match was found:


import re


txt = "The rain in Spain"

x = re.findall("Portugal", txt)

print(x)

The search() Function

The search() function searches the string for a match, and returns a Match object if there is a match.


If there is more than one match, only the first occurrence of the match will be returned:


Example

Search for the first white-space character in the string:


import re


txt = "The rain in Spain"

x = re.search("\s", txt)


print("The first white-space character is located in position:", x.start())

If no matches are found, the value None is returned:


Example

Make a search that returns no match:


import re


txt = "The rain in Spain"

x = re.search("Portugal", txt)

print(x)

The split() Function

The split() function returns a list where the string has been split at each match:


Example

Split at each white-space character:


import re


txt = "The rain in Spain"

x = re.split("\s", txt)

print(x)

You can control the number of occurrences by specifying the maxsplit parameter:


Example

Split the string only at the first occurrence:


import re


txt = "The rain in Spain"

x = re.split("\s", txt, 1)

print(x)

The sub() Function

The sub() function replaces the matches with the text of your choice:


Example

Replace every white-space character with the number 9:


import re


txt = "The rain in Spain"

x = re.sub("\s", "9", txt)

print(x)

You can control the number of replacements by specifying the count parameter:


Example

Replace the first 2 occurrences:


import re


txt = "The rain in Spain"

x = re.sub("\s", "9", txt, 2)

print(x)

Match Object

A Match Object is an object containing information about the search and the result.


Note: If there is no match, the value None will be returned, instead of the Match Object.


Example

Do a search that will return a Match Object:


import re


txt = "The rain in Spain"

x = re.search("ai", txt)

print(x) #this will print an object

The Match object has properties and methods used to retrieve information about the search, and the result:


.span() returns a tuple containing the start-, and end positions of the match.

.string returns the string passed into the function

.group() returns the part of the string where there was a match

Example

Print the position (start- and end-position) of the first match occurrence.


The regular expression looks for any words that starts with an upper case "S":


import re


txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.span())

Example

Print the string passed into the function:


import re


txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.string)

Example

Print the part of the string where there was a match.


The regular expression looks for any words that starts with an upper case "S":


import re


txt = "The rain in Spain"

x = re.search(r"\bS\w+", txt)

print(x.group())

Note: If there is no match, the value None will be returned, instead of the Match Object.