Академический Документы
Профессиональный Документы
Культура Документы
3
Inheritance
• Classes can inherit functionality of other classes. If an object is
created using a class that inherits from a superclass, the object will
contain the methods of both the class and the superclass.
• Inheritance is when a class uses code constructed within another
class. If we think of inheritance in terms of biology, we can think of a
child inheriting certain traits from their parent. That is, a child can
inherit a parent’s height or eye color. Children also may share the
same last name with their parents.
• Classes called child classes or subclasses inherit methods and
variables from parent classes or base classes.
Parent Classes/Base Classes
• We create another class called Programmer. This looks very much like
a standard class except than User is given in the parameters. This
means all functionality of the class User is accessible in the
Programmer class.
class Programmer(User):
def __init__(self, name):
self.name = name
def doPython(self):
print "Programming Python"
Detail of example
• Brian is an instance of User and can only access the method printName.
Diana is an instance of Programmer, a class with inheritance from User,
and can access both the methods in Programmer and User.
class User:
name = ""
def __init__(self, name):
self.name = name
def printName(self): print "Name = " + self.name
class Programmer(User):
def __init__(self, name):
self.name = name
def doPython(self):
print "Programming Python"
brian = User("brian")
brian.printName()
diana = Programmer("Diana")
diana.printName()
diana.doPython()
Name = brian
Name = Diana
output
rogramming Python
Example 2
• Let’s create a Fish parent class that we will later use to construct
types of fish as its subclasses. Each of these fish will have first names
and last names in addition to characteristics.
class Fish:
def __init__(self, first_name, last_name="Fish"):
self.first_name = first_name
self.last_name = last_name
This is because the method live_with_anemone() belongs only to the Clownfish child class, and not the Fish parent class.
Latihan
1) Modifikasi skrip program dari Example 1 agar memenuhi kriteria berikut: - Gunakan Teori Inheritance tentang Super
Kelas User, properti : first name dan method printName
Kelas Programmer (anak kelas dari kelas User), properti lastName dan method printLastName
Buat objek dari user dan kelas programmer yang bisa menampilkan firstName dan LastName
2) Buatlah program untuk kriteria berikut ini
• Kelas Orang
Property : nama
• Sub Kelas Orang: Mahasiswa dan Pegawai
property mhs : npm
Pegawai : nip
Nama Mhs :Kelas Mhs nama, npm, semester
• Sub Kelas Pegawai:Dosen dan Karyawan
property dosen:nidn
Tampilkan :
Nama Dosen :Kelas Dosen nama, nip,nidn
Nama Karyawan :Kelas Karyawan nama,nip