Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Tutorial_ Inheritance

This document is a tutorial on Python, focusing on the concept of inheritance in object-oriented programming. It explains how classes can inherit attributes and methods from other classes, providing examples with a Person and Employee class. The tutorial also covers method overriding and overloading, highlighting the differences between Python and C++ in these contexts.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Tutorial_ Inheritance

This document is a tutorial on Python, focusing on the concept of inheritance in object-oriented programming. It explains how classes can inherit attributes and methods from other classes, providing examples with a Person and Employee class. The tutorial also covers method overriding and overloading, highlighting the differences between Python and C++ in these contexts.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Properties vs. getters and setters


Next Chapter: Multiple Inheritance

Inheritance

Follow Bernd Klein,


the author of this
Introduction website, at Google+:
Bernd Klein on
Python 3
Google
Tutorial
Bernd Klein on
The Origins of Facebook
Python
Starting with
Python: The Search this website:
Interactive Shell
Executing a Go
Script
Indentation This topic in German
Data Types and / Deutsche
Variables Übersetzung:
Vererbung
Operators
Sequential Data
Types: Lists and
Training Classes
Strings
This website aims at
List
providing you with
Manipulations
educational material
Shallow and suitable for self-
Deep Copy learning.
Dictionaries Nevertheless, it is
Sets and Frozen faster and more
Sets efficient to attend a
An Extensive "real" Python course
in a classroom, with
Example Using
an experienced
Sets
trainer. So why not
input via the attend one of the live
keyboard Python courses
Conditional
Statements Every object-oriented programming language would not be worthy to look at or use, if it weren't to support inheritance. Of course, Python supports inheritance, it even supports multiple inheritance.
Loops, while Classes can inherit from other classes. A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir
Loop class or child class. Superclasses are sometimes called ancestors as well. There exists a hierarchy relationship between classes. It's similar to relationships or categorizations that we know from real life. Think about
For Loops vehicles, for example. Bikes, cars, buses and trucks are vehicles. pick-ups, vans, sports cars, convertibles and estate cars are all cars and by being cars they are vehicles as well. We could implement a vehicle class
in Python, which might have methods like accelerate and brake. Cars, Buses and Trucks and Bikes can be implemented as subclasses which will inherit these methods from vehicle.
Difference
between
interators und
Syntax and Simple Inheritance Example
Iterables
Output with Print
We demonstrate inheritance in a very simple example. We create a Person class with the two attributes "firstname" and "lastname". This class has only one method, the Name method, essentially a getter, but we
Formatted output
don't have an attribute name. This method is a further example for a "getter", which creates an output by creating it from more than one private attribute. Name returns the concatenation of the first name and the
with string last name of a person, separated by a space. It goes without saying that a useful person class would have additional attributes and further methods. in Strasbourg, Paris,
modulo and the London, Berlin,
format method This chapter of our tutorial is about inheritance, so we need a class, which inherits from Person. So far employees are Persons in companies, even though they may not be treated as such in some firms. If we Munich, Hamburg,
Functions created an Employee class without inheriting from Person, we would have to define all the attributes and methods in the Employee class again. This means we would create a design and maybe even a data Frankfurt, or Lake
Recursion and redundancy. With this in mind, we have to let Employee inherit from Person. Constance by Bernd
Recursive Klein, the author of
The syntax for a subclass definition looks like this: this tutorial?
Functions
Parameter class DerivedClassName(BaseClassName):
Passing in pass
In-house
Functions
Of course, usually we will have an indented block with the class attributes and methods instead of merely a pass statement. The name BaseClassName must be defined in a scope containing the derived class Training
Namespaces
definition. With all this said, we can implement our Person and Employee class: Courses
Global and Local
Variables
If you like it, we will
Decorators class Person: come to your
Memoization with company or institute
def __init__(self, first, last):
Decorators and provide a special
self.firstname = first
Read and Write self.lastname = last training for your
Files employees, as we've
Modular def Name(self): done it many times in
return self.firstname + " " + self.lastname Amsterdam (The
Programming
Netherlands), Berlin
and Modules class Employee(Person): (Germany), Bern
Packages in (Switzerland), Basel
Python def __init__(self, first, last, staffnum):
Person.__init__(self,first, last) (Switzerland), Zurich
Regular self.staffnumber = staffnum (Switzerland),
Expressions Frankfurt (Germany),
Regular def GetEmployee(self): Locarno
return self.Name() + ", " + self.staffnumber (Switzerland), Den
Expressions,
Advanced Haag (The Hague),
x = Person("Marge", "Simpson")
Hamburg, Munich
Lambda y = Employee("Homer", "Simpson", "1007")
(Germany),
Operator, Filter,
print(x.Name()) Bucharest (Romania),
Reduce and Map Toronto (Canada),
print(y.GetEmployee())
List Edmonton (Canada),
Comprehension and many other
Iterators and Our program returns the following output: cities. We do training
Generators courses in England,
Exception Switzerland,
$ python3 person.py Liechtenstein,
Handling Marge Simpson Austria, Germany,
Tests, DocTests, Homer Simpson, 1007
France, Belgium, the
UnitTests Netherlands,
Object Oriented Luxembourg,
The __init__ method of our Employee class explicitly invokes the __init__method of the Person class. We could have used super instead. super().__init__(first, last) is automatically replaced by a call to the
Programming Romania, UK, Italy,
superclasses method, in this case __init__:
Class and Spain and other
Instance def __init__(self, first, last, staffnum): locations in Europe
Attributes super().__init__(first, last) and in Canada.
self.staffnumber = staffnum
Properties vs.
This way you will get
getters and
Please note that we used super()) without arguments. This is only possible in Python3. We could have written "super(Employee, self).__init__(first, last, age)" which still works in Python3 and is compatible with a perfect training up
setters Python2. to your needs and it
Inheritance will be extremely cost
Multiple efficient as well.
Inheritance Overloading and Overriding
Magic Methods Contact us so we can
and Operator Instead of using the methods "Name" and "GetEmployee" in our previous example, it might have been better to put this functionality into the "__str__" method. In doing so, we gain a lot, especially a leaner design. find the ideal course
Overloading We have a string casting for our classes and we can simply print out instances. Let's start with a __str__ method in Person: to meet your needs.
OOP, Inheritance
class Person:
Example
Slots
Skilled Python
def __init__(self, first, last):
Programmers
Classes and self.firstname = first
Class Creation self.lastname = last
You are looking for
Road to def __str__(self): experienced Python
Metaclasses return self.firstname + " " + self.lastname developers or
Metaclasses programmers? We
class Employee(Person):
Metaclass Use can help you, please
Case: Count def __init__(self, first, last, staffnum): contact us.
Function Calls super().__init__(first, last)
Abstract Classes self.staffnumber = staffnum Quote of the
Day:
x = Person("Marge", "Simpson")
Object-oriented y = Employee("Homer", "Simpson", "1007") "The internet could
Programming be a very positive
print(x) step towards
print(y) education,
"Certainly not every
good program is organisation and
The output looks like this: participation in a
object-oriented, and
not every object- $ python3 person2.py meaningful society."
oriented program is Marge Simpson (Noam Chomsky)
good." Homer Simpson
(Bjarne Stroustrup,
Danish computer First of all, we can see that if we print an instance of the Employee class, the __str__ method of Person is used. This is due to inheritance. The only problem we have now is the fact that the output of "print(y)" is
scientist, best known not the same as the "print(y.GetEmployee())". This means that our Employee class needs its own __str__ method. We could write it like this:
for the creation and
the development of
def __str__(self): Data Protection
return self.firstname + " " + self.lastname + ", " + self.staffnumber Declaration
the widely used C++
programming But it is a lot better to use the __str__ method of Person inside of the new definition. This way, we can make sure that the output of the Employee __str__method will automatically change, if the __str__ method
language.) Data Protection
from the superclass Person changes. We could, for example, add a new attribute age in Person:
Declaration
"Object-oriented
programming is an class Person:
exceptionally bad
idea which could only def __init__(self, first, last, age):
have originated in self.firstname = first
self.lastname = last
California."
self.age = age
(Edsger Dijkstra,
(Dutch computer def __str__(self):
Scientist, 1930-2002) return self.firstname + " " + self.lastname + ", " + str(self.age)

Dijkstra also said: class Employee(Person):


"... what society
overwhelmingly asks def __init__(self, first, last, age, staffnum):
super().__init__(first, last, age)
for is snake oil. Of
self.staffnumber = staffnum
course, the snake oil
has the most def __str__(self):
impressive names - return super().__str__() + ", " + self.staffnumber
otherwise you would
be selling nothing -
like "Structured x = Person("Marge", "Simpson", 36)
y = Employee("Homer", "Simpson", 28, "1007")
Analysis and Design",
"Software print(x)
Engineering", print(y)
"Maturity Models",
"Management We have overridden the method __str__ from Person in Employee. By the way, we have overridden __init__ also. Method overriding is an object-oriented programming feature that allows a subclass to provide a
Information different implementation of a method that is already defined by its superclass or by one of its superclasses. The implementation in the subclass overrides the implementation of the superclass by providing a method
Systems", with the same name, same parameters or signature, and same return type as the method of the parent class.
"Integrated Project
Support Overwriting is not a different concept but usually a term wrongly used for overriding!
Environments"
"Object Orientation" In the context of object-oriented programming, you might have heard about "overloading" as well. Overloading is the ability to define the same method, with the same name but with a different number of
and "Business arguments and types. It's the ability of one function to perform different tasks, depending on the number of parameters or the types of the parameters.
Process Re-
engineering" Let's look first at the case, in which we have the same number of parameters but different types for the parameters. When we define a function in Python, we don't have to and we can't declare the types of the
parameters. So if we define the function "successor" in the following example, we implicitly define a family of function, i.e. a function, which can work on integer values, one which can cope with float values and so.
Of course, there are types which will lead to an error if used:
Japanese Food
and OOP
>>> def successor(number):
... return number + 1
"Public opinion is that ...
both OOP and >>> successor(1)
Japanese food are 2
"good and good for >>> successor(1.6)
you", and both 2.6
>>> successor([3,5,9])
simple and pretty.
Traceback (most recent call last):
And they are! But File "<stdin>", line 1, in <module>
that doesn't File "<stdin>", line 2, in successor
automatically make TypeError: can only concatenate list (not "int") to list
them intuitive, much >>>
less easy. Both are,
in fact, much harder
than they look.",
Sean M. Burke "When You can skip the following paragraphs with the comparisons with C++, if you want to.
given a programming
project, you don't This course is not about C++ and we have so far avoided using any C++ code. We want to make an exception now, so that you can see, how overloading works in C++. While we had just one definition in Python,
"solve" anything by we have two function definitions in C++, i.e. one for the type "int" and one for "double":
declaring that this
project will be done
in OOP, any more #include <iostream>
#include <cstdlib>
than you "solve"
anything be using namespace std;
surveying a set of
ingredients and int successor(int number) {
declaring that they return number + 1;
are to be cooked }
Japanese-style.",
double successor(double number) {
Sean M. Burke
return number + 1;
}
This website is int main() {
supported by:
cout << successor(10) << endl;
cout << successor(10.3) << endl;
Linux and Python
Courses and return 0;
Seminars }

Having a function with a different number of parameters is another way of function overloading. The following C++ program shows such an example. The function f can be called with either one or two integer
arguments:

#include <iostream>
using namespace std;

int f(int n);


int f(int n, int m);

int main() {

cout << "f(3): " << f(3) << endl;


cout << "f(3, 4): " << f(3, 4) << endl;
return 0;
}

int f(int n) {
return n + 42;
}
int f(int n, int m) {
return n + m + 42;
}

This doesn't work in Python, as we can see in the following example. The second definition of f with two parameters redefines or overrides the first definition with one argument. Overriding means that the first
definition is not available anymore. This explains the error message:

>>> def f(n):


... return n + 42
...
>>> def f(n,m):
... return n + m + 42
...
>>> f(3,4)
49
>>> f(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 2 arguments (1 given)
>>>

If we need such a behaviour, we can simulate it with default parameters:

def f(n, m=None):


if m:
return n + m +42
else:
return n + 42

The * operator can be used as a more general approach for a family of functions with 1, 2, 3, or even more parameters:

def f(*x):
if len(x) == 1:
return x[0] + 42
else:
return x[0] + x[1] + 42

Previous Chapter: Properties vs. getters and setters


Next Chapter: Multiple Inheritance

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like