Course 4 – Class inheritance and working with files

In this course, we’ll continue our adventure with classes.
Let’s go with the example I gave last course.

Inheritance

Let’s talk about inheritance.
We want to reuse the code we have, and that means placing code into functions, or creating base classes we can inherit variables and functions.

Let’s assume we have a class called Human.

The function called __init__ is the constructor of the class – this is called when the object is created.

Now let’s create a class called Worker, which inherit from our base class Human.

Although the Worker class is empty, it inherits all the functions and variables from the base class.

For example, we can do the following:

If we override the init function, we will no longer inherit the parent’s init function – so we have to call it ourselves.

an alternative is to use the super() construction

Working with files

If we want to open a file, we call open and assign it to a variable:

If we want to read the file’s content, we use the function read on the object

If we want to read the file line by line:

we could use readline in a loop:

We also need to close the file when we’re done with it:

And if we want to write in files, we use the write function – but this time we need to open the file with a parameter:

Lists

Lists are collections of data, and they look like this:

If we want to trim the list (get only parts of it, we can do the following:

And if we want to loop in the list, we use the usual for:

Homework

Create a class that is responsible for handling files, and derived classes (one for opening a file, and one for writing to a file).

The derived classes should receive the file name, and send it further to the base class.

The class that is responsible for writing should have a list of lists, and write each entry from the list on a line => so we will have multiple lines with multiple entries on each line.

The class that is responsible for reading should contain a list, and for each line read from our already-written file, we add an entry in our list containing the data from that line.

You may also like...