0% found this document useful (0 votes)
23 views16 pages

Lab2 - Python Programming Basics

Uploaded by

fersd2018
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views16 pages

Lab2 - Python Programming Basics

Uploaded by

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

HCIP-Datacom-Network Automation Developer Lab Guide

2 Python Programming Basics

2.1 Introduction to Experiment


This experiment uses independent code practices of each module to help readers
master the Python3 syntax.

● Basic data types of Python


● Deep copy and shallow copy
● Flow control
● Functions
● Operations on files
● Troubleshooting
● Object-oriented programming

It is recommended to learn this guide with the official Python Tutorial,


https://docs.python.org/3/tutorial/index.html.

2.2 Code Practices


After Anaconda3 is installed on the local PC, open Jupyter Notebook and create a
Python3 notebook file. (You can also use other compilers for the experiment, such
as Pycharm.)

2020-09-24 Huawei confidential. Page 15 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

The title in the red box is the default title, and you can double-click the title to
change the file name.

The blue box in the following figure is the code input box. After the code is
complete, click Run to run the code.

2.2.1 Python Data Types


Python has rich data types, including numerics, strings, lists, tuples, dictionaries,
and sets. This section describes the characteristics of different data types using
code practices. For details, see "Built-in Types" in the Python standard library.
https://docs.python.org/3.8/library/index.html.

2.2.1.1 Data Type: Numerics


This data type is used to store numeric values, and it is immutable, which means
that, if it is changed, a new object will be assigned.

Note that Boolean operations in Python use keywords instead of operators to


express “and/or/not”.

print(True+False) # The output is 1. By default, 1 indicates True, and 0 False.


print(True or False) # True is displayed, and the "or" operation is performed.
Print(5//2) # The output is 2, and “//” is the rounding operator.
Print(5%2) # The output is 1, and “%” is the modulo operator.
print(3**2) # The output is 9, and “**” indicates the power operation.

2020-09-24 Huawei confidential. Page 16 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

print(5+1.6) # The output is 6.6. By default, the sum of numbers in different precisions follow the highest
precision of the numbers.

2.2.1.2 Data Type: Strings


A string consists of digits, letters, and underscores (_). Objects are created using
single, double, or triple quotation marks.

Basic operations on strings:

S = 'python' # Assign ‘python’ to variable S.


# len(obj): Return the object length.
print(len(S)) # Output 6.

print(S[0],S[1],S[-1]) # Output pyn and obtain elements based on the index.


print(S+'1',S*2) # Output python1 pythonpython: merge and repeat.

Immutability of strings:

S = 'python' # Assign a value to the variable.


S[0] = 'Z' # Program exception, as the string cannot be changed.
S1 ='Z'+S[1:] # A new string, Zython, is generated and assigned to S1.
# S[1:] indicates the string following the first character, that is, ython.
print("S:%s,S1:%s"%(S,S1)) # Output S:python, S1:Zython. %s prints the character string.

Common operations on strings:

S = "python" # Assign a value to the variable.

# str.split(str="", num=-1): The string is split by separator. If the “num”argument has a value, the string is
split into num+1 substrings. The value “-1” indicates that all strings are split.
print(S.split('h')) # Output ['pyt','on'], and split the string based on “h”.

# str.replace(old, new[, max]): A string generated after “old” in the string is replaced with “new”. If the third
argument “max” is specified, this replacement can take place for not more than max times.
print(S.replace('py','PY')) # PYthon: Replace “py” in the string with “PY”.

# str.upper(): Return the value after lowercase letters are converted to uppercase letters.
print(S.upper()) # PYTHON

# str.lower(): Return the value after uppercase letters are converted to lowercase letters.
print('PYTHON'.lower()) # Output python. The string is converted into lowercase letters.

line='aa,bb,ccc,dd\n' #”\n” is a line feed character.

# str.join(sequence): “sequence” indicates a sequence to be joined. In the output, the new string generated
after the elements are specified in the sequence is returned.
print(''.join(['life', 'is' ,'short'])) # Output “life is short” and “join” joins the string.

hw12= '%s %s %d' % ('hello', 'world', 12) # Format the string.


print(hw12) # Output “hello world 12”.

2020-09-24 Huawei confidential. Page 17 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.1.3 Data Type: Lists


Lists can implement data structures of most set classes. It supports characters,
numbers, strings, and even lists (that is, nesting). It is identified by [].

● Common operations on lists:


animals = ['cat', 'dog', 'monkey'] # Define the list animals.

# list.append(obj): Add a new object to the end of the list.


animals.append(‘fish’) # Append an element.
print(animals) # Output ['cat', 'dog', 'monkey', 'fish'].

# list.remove(obj): Remove the first match for a value in the list.


animals.remove(‘fish’) # Delete the element “fish”.
print(animals) # Output ['cat', 'dog', 'monkey'].

# list.insert(index, obj): Insert a specified object to a specified position in the list. The index indicates
the position.
animals.insert(1,’fish’) # Insert the element “fish” at the position of subscript 1.
print(animals) # Output ['cat', 'fish', 'dog', 'monkey'].

# list.pop([index=-1]): Remove the element (the last element by default) corresponding to the
subscript in the list. The index indicates the subscript.
animals.pop(1) # Delete the element whose subscript is 1.
print(animals) # Output ['cat', 'dog', 'monkey'].

● Traverse and obtain the elements and indexes.


# enumerate(sequence): Return an index sequence consisting of a data object that can be traversed
and list the data and subscripts. This function is usually used in the “for” loop.
for i in enumerate(animals):
print(i) # Index formed by element subscripts and elements.

Output:
(0, cat)
(1, dog)
(2, monkey)

● List derivations
squares = [x*2 for x in animals] # Generate a list of elements that comply with rules in batches.
print(squares) # ['catcat ', 'dogdog ', 'monkeymonkey ']

● Sorting
list.sort(cmp=None, key=None, reverse=False): The “cmp” parameter is
optional. If it is specified, the method of this parameter is used for sorting.
“key” is an element used for comparison. “reverse” indicates the sorting rule,
and “False” indicates the ascending order.
list1 = [12,45,32,55] # Define a new list, list1.
list1.sort() # Sort the list.
print(list1) # Output [12,32,45,55].

# list.reverse(): Element in the reverse list.


list1.reverse() # Reverse the list.
print(list1) # Output [55,45,32,12]

2020-09-24 Huawei confidential. Page 18 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.1.4 Data Type: Tuples


A tuple is identified by () and internal elements are separated by commas (,).

A tuple cannot be assigned a value for a second time, which is similar to a read-
only list.

Common operations on tuples:

T=(1,2,3) # Create a tuple.


print(T+(4,5)) # Combine tuples and output (1, 2, 3, 4, 5).
t=(42,) # A tuple with only one element, which is different from a number.
tuple1 = (12,45,32,55,[1,0,3]) # Create a tuple.
tuple1[0] = "good" # Program exception, as the tuple is immutable and a value cannot be
assigned to it.
tuple1[4][0] = 2 # Values cannot be assigned to mutable elements. In the example, the
elements are in the [1,0,3] list.
print(tuple1) # (12,45,32,55,[2,0,3])

2.2.1.5 Data Type: Dictionaries


A dictionary is a flexible built-in data structure and is identified by {}.

A dictionary consists of indexes (keys) and their values. Compared with a list,
elements in a dictionary are saved as keys instead of offsets.

Common operations on dictionaries:

# Three operations to assign values to dictionaries:


x = {'food':'Spam','quantity':4,'color':'pink'}
x = dict(food='Spam',quantity=4, color='pink')
x = dict([("food", "Spam"),("quantity", "4"),("color","pink")])

# dict.copy(): Copy data.


d =x.copy()
d['color'] = 'red'
print(x) # {'food':'Spam','quantity':4,'color':'pink'}
print(d) # {'food':'Spam','quantity':4,'color':'red'}

# Element access.
print(d['name']) # Error information is obtained.
print(d.get('name')) # Output none.
print(d.get('name','The key value does not exist.')) # Output “The key value does not exist”.
print(d.keys()) # Output “dict_keys(['food', 'quantity', 'color'])”.
print(d.values()) # Output “dict_values(['Spam', 4, 'red'])”.
print(d.items()) # Output “dict_items([('food', 'Spam'), ('quantity', 4), ('color', 'red')])”.
d.clear() # Clear all data in the dictionary.
print(d) # Output “{}”.
del(d) # Delete the dictionary.

2.2.1.6 Data Type: Sets


A set is an unordered sequence of unrepeatable elements. Sets can be created
using braces {} or the set() function.

2020-09-24 Huawei confidential. Page 19 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Common operations on sets:

sample_set = {'Prince', 'Techs'}


print('Data' in sample_set) # Output “False”. “in” is used to check whether an element exists in the set.

# set.add(obj): Add an element to a set. If the element to be added already exists in the set, no operation is
performed.
sample_set.add('Data') # Add element “Data” to the set.
print(sample_set) # Output “{'Prince', 'Techs', 'Data'}”.
print(len(sample_set)) # Output “3”.

# set.remove(obj): Remove a specified element from a set.


sample_set.remove('Data') # Delete element “Data”.
print(sample_set) # {'Prince', 'Techs'}

list2 = [1,3,1,5,3]
print(list(set(list2))) # Output [1,3,5]. The unique set elements are used to de-duplicate the list.
print(list(set(list2))) # Output the [1,3,5] list.
sample_set = frozenset(sample_set) # Immutable set.

2.2.2 Deep Copy and Shallow Copy


In Python, value assignment to an object is actually a reference to the object.
When an object is created and assigned to another variable, Python does not copy
the object but copies its reference.

In this experiment, the copy module in Python is used to differentiate deep copy
from shallow copy.

import copy # The current program calls the copy module.


Dict1 = {'name':'lee', 'age':89, 'num':[1,2,8]} # Create a dictionary.
Dict_copy = Dict1.copy() # Shallow copy.
Dict_dcopy = copy.deepcopy(Dict1) # Deep copy.
Dict2=Dict1 # Shallow copy. Directly assign a value to the object.
Dict1['num'][1] = 6 # Change the value of the nested list in the original data.
print('Dict1:'+str(Dict1)+"\n",'Dict_copy:'+ str(Dict_copy)+"\n",'Dict_dcopy:'+ str(Dict_dcopy)+
"\n",'Dict2:'+str(Dict2))

Output:

Dict1:{‘name’:’lee’, ‘age’:89, ‘num’:[1,6,8]}


Dict_copy :{'name':'lee', 'age':89, 'num':[1,6,8]} # Shallow copy modifies data..
Dict_dcopy :{'name':'lee', 'age':89, 'num':[1,2,8]} # Deep copy does not modify data.
Dict2:{'name': 'lee', 'age': 89, 'num': [1, 6, 8]} # Value assignment to an object is shallow copy, and
data is modified.

2.2.3 if Statement
The programming language provides various control structures, which allow more
complex execution paths. if statement is one of the control structures, and is used
to execute subsequent instructions after a condition is matched.

2020-09-24 Huawei confidential. Page 20 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

In this example, a Python script is compiled to receive a score entered by a user


and determine the level of the score. You can use if statement in Python to
implement this function.

# Determine the level of entered score.


# input(): Receive input data.
score = input("Please enter your score.") # The input function receives input, which is a string.

# try: except Exception: … is a Python statement used to capture exceptions. If an exception occurs in the
statement in “try”, the statement in “except “is executed.
try:
score = float(score) # Convert the score to a number.
if 100>=score>=90: # Check whether the entered value is greater than the score of a
level.
print("Excellent") # Generate the level when conditions are met.
elif 90 > score >= 80:
print("good")
elif 80>score>=60:
print("medium")
elif 60>score>=0:
print("bad")
else:
raise
except Exception:
print("Enter a correct score.")

2.2.4 Loop Statement


A loop statement can execute a statement or statement group multiple times. This
example describes two types of loops: for and while.

● for loop
The for loop can traverse any sequence of items, such as a list or string.
In this example, a Python script is compiled to print the multiplication table.
for i in range(1,10): # Define the outer loop.
for j in range(1,i+1): # Define the inner loop.
print ("%d * %d = %2d" % (i, j, i*j), end=" \t ") # Print a string in format to align the print.
print() # The “end” attribute sets the end symbol of the print, which is /n by default.

Output:
1*1= 1
2*1= 2 2*2= 4
3*1= 3 3*2= 6 3*3= 9
4*1= 4 4*2= 8 4*3=12 4*4=16
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

● while loop

2020-09-24 Huawei confidential. Page 21 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

In Python programming, the while statement is used to cyclically execute a


program. That is, under a certain condition, a program is cyclically executed
to process the same task that needs to be repeatedly processed.
When the condition is met, the statement is executed cyclically. To end the
loop, use break or continue.
# while loop
i=0 # Create the variable i.
while i<9: # Set a condition for the loop.
i+=1 # The value of i increases by 1 in each loop.
if i == 3: # Check whether the conditions are met.
print("End the current loop.")
continue # execute “continue” to end the current loop.
if i == 5:
print("End the current big loop.")
break # End the current big loop.
print(i)

Output:
1
2
End the current loop.
4
End the current big loop.

2.2.5 Customizing Functions


A function is a piece of code, organized and reusable. It can improve code
utilization and modularity of the program. Python provides many built-in
functions, such as print(). You can also create functions, that is, user-defined
functions.

This section describes how to customize functions.

● Define a function.
Use the “def” keyword to define a function, which can call the function (print
information).
def Print_Hello(): # Function name, no input value.
print("Hello, Python.") # Output
Print_Hello() # Call function.

Output:
Hello, Python.

● Parameter transfer for a function and default parameters


A function can be customized to print parameters transferred in different
ways.
def hello(greeting='hello',name='world'): # Set default parameters.
print('%s, %s!' % (greeting, name)) # Format the output.
hello() #hello, world. If no parameter is specified, the default parameter is used.
Hello ('Greetings') # Greetings, world. This is a position parameter.
hello(name=’Huawei’) # hello, Huawei. This is a keyword parameter.

2020-09-24 Huawei confidential. Page 22 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

Hello ('Greetings', 'universe') # Greetings, universe. This is a position parameter.

Output:
hello, world!
Greetings, world!
hello, Huawei!
Greetings, universe!

● Length-variable parameters
A function with length-variable parameters can process parameters more
than defined. In this case, * indicates a tuple-type parameter and ** indicates a
dictionary-type parameter.
def test (a, b, *c, **d):
print (a)
print (b)
print (c)
print (d)
test (1,2,3,4,5,6,x=10,y=11) # The transfered parameters are automatically distinguished as the tuple or
dictionary type.

Output:
1
2
(3, 4, 5, 6)
{'x': 10, 'y': 11}

● Returned values
The returned value of a function is the result that the function returns to the
caller after completing the method. Use the return statement.
def plus_one (number):
return int(number)+1
plus_one (10)

Output:
11

2.2.6 I/O Operations


The standard library of Python is large and provides a wide range of modules. File
I/O is one of the built-in modules. For more operations on the standard library,
see the official document at https://docs.python.org/3.8/library/index.html.

Python I/O operations are performed to read and write files. Generally, you can
use the open function to perform the operations.

File Mode Description

r Read-only, default. The file pointer is placed in the file header.

w Write-only. The file pointer is placed in the file header, and the file
overwrites the original content.

2020-09-24 Huawei confidential. Page 23 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

File Mode Description

a Append. The pointer is placed at the end of the file. If no file exists,
a file is created.

rb Read-only files in binary format, such as audio or image files.

wb Write-only files in binary format.

ab Append files in binary format.

r+ Read and write. The file pointer is placed in the file header.

w+ Read and write. If a file exists, the file will be overwritten. If no file
exists, a file is created.

a+ Append, read, and write. If no file exists, a file is created.

● Write a file
f = open("text.txt", 'w') # Open the text.txt file. If the file does not exist, a new file is created. w: write
mode
Str = input("Please enter the content to be written.") # The built-in function “input” gets the input of
the console.
f.write(Str) # Write “Str” to file f.
f.close() # Close the file.

Output:

Enter the content to be written, “Python file operation”.


The text.txt file is generated in the same directory.

● Read a file
The read method is used to read files. If read() is not specified, all content is
read.
f = open("text.txt", 'r') # r indicates that the file is read.
print(f.read(6)) # Read six characters and move the cursor six characters backward.
print(f.read()) # Read from the current position of the cursor to the end.
f.close()

Output:
Python
file operation

● Use the context manager to operate the file.


The context manager defines the scope of using the resources. Resources are
allocated at the start of the code and released at the end of the code. This

2020-09-24 Huawei confidential. Page 24 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

simplifies code and improves its readability. The context manager works with
the “with” statement. The basic syntax is as follows:
“with” context expression [“as” resource object]: # “as” indicates that the
return value of the context is assigned to the resource object.
Object operation:
with open("text1.txt", 'w') as f: # Use the “with” statement to write data to the file.
f.write("python file operation")
with open("text1.txt", 'r') as f: # Use the “with” statement to read the file content.
print(f.read())

Output:
Python file operation

There are more methods for file operations, such as reading a line of
readlines, positioning files with “tell”, and finding files with “seek”. For details,
see Python Tutorial.

2.2.7 Exception Handling


Errors that occur during program execution are called exceptions. Common
exceptions include syntax errors (SyntaxError), undeclared variables (NameError),
and access to unknown attributes (AttributeError). Python has a powerful
troubleshooting mechanism to accurately report error information, which helps
developers locate faults.

Python uses the “try-except” statement to handle exceptions. The “try” statement
is used to check exceptions, and the “except” statement to capture exceptions.

● Create exceptions.
First, let's create an exception where the divisor in a division is 0.
num1 = input('Please enter the first digit:')
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)) #%f indicates a
floating point number.

Output:
Please enter the first digit: 10
Please enter the second digit: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-10-5cc9c0d19753> in <module>
1 num1 = input('Please enter the first digit:')
2 num2 = input('Please enter the second digit:')
----> 3 print ('The first number divided by the second number is %f'%(int(num1)/int(num2)))
4
ZeroDivisionError: division by zero

The cause of exception is ZeroDivisionError. You can capture this exception


to keep the program running properly.
● Use “try-except” to generate code.

2020-09-24 Huawei confidential. Page 25 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

The “try-except” statement is used to capture the ZeroDivisionError exception


and display “The second digit cannot be 0”.
try:
num1 = input('Please enter the first digit:’)
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)))
except ZeroDivisionError:
print('The second digit cannot be 0.')

Output:
Please enter the first digit: 10.
Please enter the second digit: 0.
The second digit cannot be 0.

The exception is successfully captured. If multiple exceptions need to be


captured, you can use multiple “except” statements in parallel to capture
different exceptions.
● Capture all exceptions.
It is very difficult to define each exception. The exception class is the parent
class of all exceptions and can represent all exceptions.
try:
num1 = input('Please enter the first digit:')
num2 = input('Please enter the second digit:')
print('The first number divided by the second number is %f'%(int(num1)/int(num2)))
except Exception as result :
print('Captured exception: %s' % result)

Output:
Please enter the first digit: hello.
Please enter the second digit: 0.
Captured exception: invalid literal for int() with base 10: 'hello'

● No exception is captured (else and finally).


If no exception is captured in the program, the program executes the “else”
statement. Sometimes this capture operation has to be terminated regardless
of whether an exception has been caught or not. In this case, the “finally”
statement can be used.
In Python, the complete exception handling format is as follows:
try:
# Statement
except:
# Code with exception
except:
# Another code with exception
else:
# Code without exception
finally:
# Code that must be executed at last, regardless of exception

2020-09-24 Huawei confidential. Page 26 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

2.2.8 Object-Oriented Programming (Class)


Class and object are important concepts in object-oriented programming. An
object is specific and a class is general to regard a group of objects with the same
characteristics and behavior.

For example, in the first case, Dog is a class and Husky is an object of the class.
Husky has all the features and behaviors of the Dog class.

2.2.8.1 Creating and Using Classes


Create the Dog class.

Each instance created based on the Dog class stores the name and age. We will
give each dog the sit () and roll_over () abilities.

class Dog(): # Use the keyword class to declare a class.


"””Simulate dog behavior (method)"””
def sit(self): # Use a function to define the method of a class. “self”
indicates itself and is always the first parameter.
"""Simulate a dog sitting when ordered"""
print("Dog is now sitting") # In the method, “self” is used to access the name attribute.
def roll_over(self):
"""Simulate a dog rolling over when ordered."""
print("Dog rolled over!")
dog = Dog() # Create an object and use Dog to save its reference.
dog.name = "Husky" # Add an attribute that indicates the name, which is Husky.
dog.sit() # Call the method.
dog.roll_over()
print (dog.name)

Output:

Dog is now sitting


Dog rolled over!
Husky

2.2.8.2 Attributes of Class


In the previous case, if you want to create an object of the Dog class, you need to
use “object name.attribute name” again, which is troublesome. To solve this
problem, Python provides a constructor method __init__ (with two underscores
before and after) to initialize the class.

In this example, the name and age attributes are initialized to the Dog class.

class Dog(): # Use the keyword class to declare a class.


"Simulate the attributes and behaviors of dog (method)"
def __init__ (self,name,age): # Initialize class attributes. The first parameter is always self, indicating the
object itself.
"""Initialize the name and age attributes."""
self.name = name
self.age = age
def sit(self): # Use the function to define a method for class to carry the self parameter.
"""Simulate a dog sitting when ordered."""

2020-09-24 Huawei confidential. Page 27 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

self.name+" is now sitting") # The method uses “self” to access the name attribute.
def roll_over(self):
"""Simulate a dog rolling over when ordered."""
print(self.name+" rolled over!")
dog = Dog("Husky",2) # Create an object and use Dog to save its reference.
print (dog.age) # Access attributes.
dog.sit() # Call the method.
dog.roll_over()

Output:

2
Husky is now sitting
Husky rolled over!

2.2.8.3 Encapsulating Classes


The process of hiding the details of properties, methods, and method
implementations is called encapsulation. Attributes are defined as private to
prevent unauthorized value assignment.

Private attributes are implemented by __ (two underscores).

class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age # Set age to a private attribute __age.
def get_age(self):
return self.__age
dog = Dog ("Husky",2)
print (dog.name)
dog.get_age() # Call the get_age() method and return parameters.
print (dog.__age) # The program reports an error, indicating that the __age attribute does not exist
and cannot be directly called by external systems.

Output:

Husky
2
AttributeError Traceback (most recent call last)
<ipython-input-23-374e764e1475> in <module>
5 dog = Dog('Husky', '2')
6 print (dog.name)
----> 7 print (dog.__age)
8
AttributeError: 'Dog' object has no attribute '__age'

2.2.8.4 Inheriting Classes


One of the main benefits of object-oriented programming is code reuse, which is
achieved through inheritance. Inheritance can be understood as the type and
subtype relationships between classes.

In this example, the subclass Husky of class Dog is constructed to inherit the
attributes and methods of the parent class. The method of subclass (parent class)

2020-09-24 Huawei confidential. Page 28 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

is used. If a subclass needs to inherit multiple classes, the method is subclass


(parent class 1, parent class 2). In this example, a subclass inherits one class.

class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age # Set age as a private attribute __age.
def get_age(self):
return self.__age
class Husky(Dog): # Declare a subclass Husky and a parent class Dog.
pass
mydog = Husky('Larry','3') # The subclass inherits the construction method of the parent class.
print (mydog.name) # The subclass inherits the name attribute of the parent class, but cannot inherit private
attributes.
mydog.get_age() # The subclass inherits the get_age() method of the parent class.

Output:

Larry
3

2.2.8.5 Class Polymorphism


In Python, polymorphism refers to the use of objects without considering object
types. Python does not care about whether an object is a parent class or subclass,
but only cares about the behavior (method) of the object.

In this example, the parent class is Dog and has the shout method. The subclasses
of Dog, Husky and Tibetan Mastiff, rewrite the shout method of the parent class.
A function sound can be defined. When calling the shout method, the program
does not care whether the object is a parent class or subclass, but cares only
whether they all have the shout method.

# The parent class is Dog and the sound is Dog shouts.


class Dog():
def __init__ (self,name,age):
self.name = name
self.__age = age
def get_age(self):
return self.__age
def shout(self):
print ('Dog shouts')

# The subclass is Husky, shouting as woo.


class Husky(Dog):
def shout(self):
print('woo')

# The subclass is Tibetan Mastiff, shouting as barking.


class Tibetan_Mastiff(Dog):
def shout(self):
print('barking')

# Define a function sound to call the shout method.


def sound(dog):

2020-09-24 Huawei confidential. Page 29 of 41


HCIP-Datacom-Network Automation Developer Lab Guide

dog.shout()

# dog1 is the object of Husky.


dog1 = Husky('Larry',3)
sound(dog1)

# dog2 is the object of Dog.


dog2=Dog('Richard',2)
sound(dog2)

# dog3 is the object of Tibetan Mastiff.


dog3= Tibetan_Mastiff('Sylvia',4)
sound(dog3)

Output:

Woo
Dog shouts
Barking

2020-09-24 Huawei confidential. Page 30 of 41

You might also like