-
Notifications
You must be signed in to change notification settings - Fork 0
/
inheritance.py
53 lines (38 loc) · 1.72 KB
/
inheritance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Inheritance allows you to pass in an existing class (i.e. parent class),
# into a new class (i.e. child class)
# PURPOSE: allows programmers to REUSE & BUILD upon exisiting classes
# E.g passing in the parent class allows the child class access to the
# init, attributes & methods within the parent class
class Person:
# Class Attributes
# goes above/outside __init__
# a variable that is shared between a class & its objects
# accessible wo an object,and can be called with the class name instead
# E.g. person.species vs obj_name.species
# Either way works regardless
species = "Human"
def __init__(self, first_name, sur_name):
self.first_name = first_name
self.sur_name = sur_name
def greeting(self):
return f"Hello my name is {self.first_name}, nice to meet you."
def introduction(self):
return f"I am {self.first_name} {self.sur_name}"
class Agent(Person):
# To add more attributes than what was provide by the parent class you need to
# override the init method itself, and pass in your desired parameters in the child class
def __init__(self, first_name, sur_name, code_name):
Person.__init__(self, first_name, sur_name)
self.code_name = code_name
# If you want to override an inherited method you can redefine it
def introduction(self):
return f"I am agent 001, agent {self.code_name}."
def reveal(self, passcode):
if passcode == 123:
return f"{self.first_name} is a an agent!"
else:
# calls method inherited from Person class
self.introduction()
a1 = Agent("John", "Smith", "Mr. A")
print(a1.introduction())
print(a1.reveal(123))