Python Lesson 14: Inheritance

Advertisements

Hello everybody,

Michael here, and today’s lesson will be on inheritance in Python. Inheritance in Python is the same concept as inheritance in Java-a child class inherits all of the methods and attributes from another class called the parent class. However, inheritance in Python is executed differently than inheritance in Java, and this post will describe how inheritance in Python works.

To demonstrate inheritance, let’s first create a parent class:

In the parent class Team, I have two functions-__init__ and printInfo. The __init__ function accesses the class’s two main parameters-teamName and Location. The printInfo function prints the String The {teamName} are located in {location}.

  • The f in the print line denote that the String I’m trying to print is an f-string literal, which is a neat way to format Strings and concatenate values.
  • When inputting the parameter names into the f-string literal, remember to use the keyword self (or whatever word you used in place of self) in front of the parameter name just as I did for self.teamName and self.location.

OK, so now let’s create an object of the Team class and execute the printInfo method:

Now let’s create a class called BasketballTeam, which will serve as a child class of the Team class:

Inheritance with Python classes is conceptually the same as inheritance with Java classes but inheritance with Python classes has much different syntax.

To create a child class in Python, use this general syntax: class ChildClass (ParentClass).

You’ll also notice that I used the pass keyword as the body of the BasketballTeam class. However, when it comes to child classes, pass doesn’t mean the class is empty. Instead, pass means that all methods and attributes from the parent class are inherited, but you don’t want to add any new methods or attributes to the child class that aren’t in the parent class.

Now let’s create an object of the BasketballTeam class and call the printInfo function:

Looks like the inheritance worked like a charm!

Now, what if we wanted to use the __init__ function for our child class instead of the pass keyword? Let’s see how we would execute that:

In this example, the child class’s __init__ function overrides the parent class’s __init__ function. However, the printInfo function is unaffected by this change.

To keep the parent class’s __init__ function, be sure to call the parent class’s __init__ function in the child class’s __init__ function:

  • As you can see, the printInfo function works the same regardless of whether I use the parent class’s __init__ function or the child class’s __init__ function.

Now, what if you wanted the child class to inherit all of the methods and attributes from the parent class? To do this, use the keyword super (with parentheses):

When using the super() keyword in a child class, keep these three things in mind:

  • Place the super() keyword in the body of the child class’s __init__ function.
  • After using the super() keyword, remember to call the __init__ function. Also remember to use all of the parameters of the child class’s __init__ function except for self (or whatever you decided to call the self parameter).
  • Super() inherits all of the methods and attributes from the parent class, so there’s no need to mention the parent class (Team in this case)

Now, what if we wanted to add an attribute that is exclusive to the child class? Let’s see how we can accomplish that:

To add an attribute that is exclusive to a child class, use this syntax: self.(name of attribute) = value of attribute. Also remember to place any new attributes in the body of the child class’s __init__ function (not the super().__init__ function call).

Now I need to make another change to my code? What could that be?:

I needed to include my new attribute yearFounded as a parameter in the child class’s __init__ function. Whenever you create a new attribute that is exclusive to the child class, you SHOULD include it as a parameter in the child class’s __init__ function. By doing so, any new attribute you created can be used as a parameter when creating an object of the child class.

  • You don’t absolutely need to include the new attribute(s) in the parameters of the child class’s __init__ function but if you don’t include them, you won’t be able to use the new attribute(s) when creating an object of the child class.

OK, but what if you also wanted to add a function exclusive to the child class? Let’s see how we can do that:

To add a function exclusive to the child class, simply create a new function in the body of the child class with self (or whatever you want to use in place of self) as the sole parameter. DO NOT place the new function in the body of the child class’s __init__ function!

As you can see here, the new function I added-teamDescription works perfectly with the child class BasketballTeam. However, watch what happens when I try to use the teamDescription function with an object of the parent class Team:

I can’t use the teamDescription function on the parent class Team because the teamDescription function is exclusive to the child class BasketballTeam; therefore, it can only be used by the child class.

Thanks for reading,

Michael

Python Lesson 13: Classes & Objects

Advertisements

Hello everybody,

It’s Michael, and today’s Python lesson will be on classes & objects in Python.

Python, like Java, is an object-oriented programming language. Everything in Python is an object, and each object in Python has its own attributes and methods (or functions in Python lingo). Classes in Python serve as object-builders (or blueprints for creating objects) just like classes in Java.

How do you create a class in Python? Let’s find out:

To create a class in Python, you simply need to use the keyword class. That’s it! No need to write public or private or anything like that in front of the class keyword like you would need to do in Java.

Alright, now let’s create an object of the class:

Creating an object of a Python class is similar to creating an object of a Java class, except in Java you would need the new keyword in front of the class name. Pretty simple right?

Now, I just demonstrated the simplest form of classes and objects. These examples wouldn’t serve you well when you’re working on any sort of Python programming project; classes and objects are more complex than what I just discussed.

To better understand classes and objects in Python, we need to understand the __init__ function. The __init__ function is built into every Python class, and it allows you to assign values to objects. Here’s an example of a class with the __init__ function:

In this class, the __init__ function has 4 parameters-self, year, month, and day. Year, month, and day are the variables for the RandomDate class.

There is also another parameter that I haven’t yet discussed-self. The self parameter refers to the class itself; it is used to access variables of the class, which in turn allows you to assign values to these variables. In the example above, I am able to access the year, month, and day variables by using self.year, self.month, and self.day, respectively.

  • Remember that in order to access the variables in the __init__ function, use this syntax: self.[variable name] = [variable name]
  • Remember that in order to access the variables in the __init__ function, use this syntax: self.[variable name] = [variable name]

You don’t absolutely have to call the first parameter self; you can name it whatever you want but it must be the first parameter of the function. Using the example above, let’s see what happens when we use another variable name instead of self:

This time, I replaced self with thedate but the code-block executed just fine since I remembered to use thedate as the first parameter.

Now, let’s add a method to class. Let’s also create a new object of the class and call the new method we created:

I added the function today to the RandomDate class and created a new object of the RandomDate class-r. The object r consists of the three main parameters of the RandomDate class-year, month, and day. The self (or thedate in this case) parameter isn’t included in the object creation, as it is only used to access the three main parameters.

Once I create the r object of the RandomDate class, I call the today function and get the output Today is September 20, 2020.

  • As you can see above, the three main parameters-2020, September, and 20-are all Strings. This is because you can only concatenate Strings with other Strings in Python. Just something to keep in mind when you’re writing your Python code.

Now that we have created an object of a class, let’s see how we can modify that object. First, let’s modify one of the properties of r:

In this example, I changed the value of day to 21 (in String format), called the today function again, and got the output Today is September 21, 2020.

Now, let’s say we wanted to get rid of the year. How do we do that? Take a look:

To delete an attribute from an object, follow this easy syntax: del [object name].[attribute to be deleted].

OK, so what if you wanted to get rid of the entire r object? This is what you would do:

To delete an entire object, just follow this very easy syntax: del [object name].

The last point I wanted to bring up regarding Python classes and objects is that, just like Python functions, they can’t be empty. However, the same empty-function workaround can be used for empty classes-simply using the keyword pass in the body of the function:

Thanks for reading,

Michael

Python Lesson 12: Lambdas & List Comprehension

Advertisements

Hello everybody,

Michael here, and today’s lesson will be on lambdas and list comprehension in Python.

First off, let’s discuss lambdas. Lambdas are small, anonymous functions (meaning nameless functions) in Python that can take any number of arguments/parameters but only one expression. Here’s the general syntax for lambda functions (and in case you didn’t figure it out, lambda functions always start with lambda):

  • lambda arguments/parameters : expression
    • Lambda functions are always just one line long!

To help you better understand lambda functions, here’s an example of a simple lambda function:

In this example, the lambda function only has 1 argument-a-and 1 expression-a**2.  Simple enough right? However, the way to call a lambda function is different from the way you would call a regular function. Since lambda functions are anonymous, you can’t simply call lambda and insert the parameter(s). You need to store the lambda function in a variable (x in this case), call the variable with a print statement, and use the parameter(s) in the variable call (in this case, x(5) is the variable call.

Now, I said lambda functions can take multiple arguments. Here’s an example of a lambda function with several arguments:

This lambda function has 3 arguments-a, b, and c-and 1 expression-a+b-c. In this example, the parameters for the lambda function are 3, 5, and 7. In lambda functions, Python assigns values to the parameters based on the order that the parameters are listed, so a is 3, b is 5, and c is 7.

Another cool thing about lambda functions is that you can use them inside regular functions. Here’s how that is possible:

In order to use a lambda function inside a regular function, first create a regular function (one that starts with def), then create a lambda function inside the regular function.

  • Notice how in this example, the regular function lambdatest has a parameter of y while the lambda function has a parameter of z. When you are creating a lambda function inside a regular function, it’s good practice to give the parameters of the lambda function and regular function different names.

However, to call the lambda function inside the regular function, you would first have to create a variable for the lambda function (in this example, the variable is funct). However, the value of the variable would be a call of the regular function. In this example, the value of the variable for my lambda function (funct) is lambdatest(3), which is a call of the regular function lambdatest

After doing this, there’s one more step. In order to call the lambda function, type (print(lambda function variable(parameters if any))); in this example the line of code you would use is print(funct(6)). After you execute this code, you will get the output of the lambda function-2.

You might be wondering why there are two different function calls with two different sets of parameters. This is because the lambda function-(2**y)-z-takes its parameters from both the lambda function (z) and the regular function (y), so in order to call the lambda function in the regular function, you would have to call both the lambda function (in the form of a variable) and the regular function. 

OK, that’s all I have for lambda functions. Now let’s delve into list comprehension.

What is list comprehension? In Python, list comprehension is a simpler and more concise method of creating lists in Python. 

Here’s an example of list creation in Python. Looks correct right?:

As you can see, there’s nothing syntactically wrong with this code. A for loop iterates through all of the elements in list2 and adds them to list1 without any errors. 

However, even though this code works fine, it’s a cumbersome way to create lists in Python. Here’s how you would create this same list with list comprehension:

Pay attention to the line list1 = [i for i in list2]. This line of code creates list1 by iterating through all of the elements in list2. The for loop in the previous example does the same thing, but this line of code is more concise. Plus, creating a list using for loops takes several lines of code, while list comprehension only takes a single line of code.

    • Personally, I think list comprehension is another great functionality of Python that I wish Java had (but unfortunately they don’t).

List comprehensions look different depending on the kind of list you’re trying to create, but all list comprehensions in Python follow this basic format:

    • name_of_list = [expression for member in iterable]

What do each of these components mean? Let’s break them down:

    • Expression-this can be any valid expression that returns a value. In the example above, i would be the expression.
      • For the example above, i alone works as an expression, but you can use something more complex for the expression if you wish.
    • Member-this represents a value in the list. In this example, i is the member that represents each individual value in the list
    • Iterable-this represents the list that the list comprehension function will iterate through. In this example, the iterable would be list2, since list1 is created by iterating through the elements in list2 one at a time.
    • List comprehension functions can have an optional fourth element-which I’ll call the conditional-that can filter elements in a list based on a certain set of criteria (I’ll discuss this more later).

Now that I’ve discussed the basics of list comprehension, let’s demonstrate an example of list comprehension using conditional logic:

In this example, list4 is created using the elements in list3 that meet the criteria defined in the if statement-i % 4 == 0. In other words, list4 will contain the elements from list3 that can be divided evenly by 4; only 3 elements from list3 meet that criteria, so list4 only contains 3 elements (12, 24, 60). 

As you can see, list comprehension is a pretty versatile functionality in Python. However, you might not have realized that list comprehension can not only iterate through a single list but can also iterate through multiple lists at once to create a super-list. Here’s an example of this:

In this example, the list z is created by iterating through the elements in two lists-[12, 24, 28] and [2,3,4]. However, the creation of list z isn’t as simple as printing out all of the elements of these two lists. Since there is an expression at the beginning of the list comprehension function-x*y-each of the values in the first list will be multiplied by each of the values in the second list and all 9 of the resulting products will be displayed.

Why will there be 9 products? We are multiplying all 3 of the elements in the first list by all 3 of the elements in the second list, and 3*3 is 9.

Thanks for reading,

Michael