7. Function
7.1 defining functions
Example 1:
#Define function: for example, define a function that outputs an odd number within 10 def Odd_number_within_10(): number1 = 0 while number1 < 10: number1 += 1 if number1 % 2 == 0: continue print number1 Odd_number_within_10()
Output is:
1 3 5 7 9
Example 2:
#Transfer information to the function: when a=15, the odd number within a is output def Odd_number(a): number1 = 0 while number1 < a: number1 += 1 if number1 % 2 == 0: continue print number1 Odd_number(15)
Output is:
1 3 5 7 9 11 13 15
In this example, a is the formal parameter and 15 is the argument.
7.2 passing arguments
For example, the following function:
# Example: output an odd number between a and B def Odd_number(a,b): number1 = 0 while number1 < a: number1 += 1 while a <= number1 < b: number1 += 1 if number1 % 2 == 0: continue print number1
(1) Position argument: the position of the argument corresponds to the position of the formal parameter one by one. In this example, a corresponds to 2 and b corresponds to 8
Odd_number(2,8)
Output is:
3 5 7
Call function more than once:
Odd_number(2,8) print ("\n") Odd_number(4,10)
Output is:
3 5 7 5 7 9
(2) Keyword arguments: there is no need to consider the order of arguments, and it also clearly indicates the purpose of each value in the function call
Odd_number(a=4,b=10)
Output is:
5 7 9
(3) Default value argument
def Odd_number(a,b=12): #When specifying the default value for a formal parameter, there can be no spaces on both sides, and so can when calling number1 = 0 while number1 < a: number1 += 1 while a <= number1 < b: number1 += 1 if number1 % 2 == 0: continue print number1 Odd_number(1)
Output is:
3 5 7 9 11
7.3 return value
Example 1:
#1. Return simple value def name(first_name,last_name): full_name = first_name + ' ' + last_name return full_name.title() #When calling the return value function, you need to provide a variable to store the returned value. a1 = name('gao','chi') print a1
Output is:
Gao chi
Example 2:
#2. Make the argument optional #When some arguments do not necessarily exist, the formal parameter can be changed into the following optional forms, so that there will be no error at run time def name1(first_name,last_name,middle_name=''): full_name1 = first_name + ' ' + middle_name + ' ' + last_name return full_name1.title() b1 = name1('gao','chi') print b1 b2 = name1('Franklin','Roosevelt','Delano') print b2
Output is:
Gao Chi Franklin Delano Roosevelt
Example 3:
#3. Return to the dictionary def name2(first_name,last_name): person = {'first':first_name ,'last': last_name} return person c1 = name2('gao','chi') print c1
Output is:
{'last': 'chi', 'first': 'gao'}
Example 4:
#4. Use function and while loop together def name3(first_name,last_name): full_name = first_name + ' ' + last_name return full_name.title() while True: print "Please tell me your name:" print "enter 'q' to quit" f_name = raw_input("First name: ") if f_name == 'q': break l_name = raw_input("Last name: ") if l_name == 'q': break name03 = name3(f_name,l_name) print "Hello, " + name03 + "!"
Input:
Please tell me your name: enter 'q' to quit First name: gao Last name: chi Please tell me your name: enter 'q' to quit First name: q
Output is:
Hello, Gao Chi!
7.4 delivery list
For example:
#Transfer list: for example, move to another list after printing #Print model functions: def print_models(unprinted_gc,printed_gc): while unprinted_gc: current_gc = unprinted_gc.pop() #Send unprinted list into list loop print "printing gc:" + current_gc printed_gc.append(current_gc) #Send the printed content to the printed list #Display model functions: def show(printed_gc): print "printed gc:" for printed_gc0 in printed_gc: #Show printed content print (printed_gc0)
(1) Modify list in function
#1. Modify the list in the function unprinted_gc0 = ['a','b','c'] printed_gc0 = [] print_models(unprinted_gc0,printed_gc0) show(printed_gc0) print unprinted_gc0 #Check whether the unprinted list has changed
Output is:
printing gc:c printing gc:b printing gc:a printed gc: c b a []
(2) The use of slicing notation prevents the function from modifying the list without affecting the operation of the program
#2. Prohibited function modification list unprinted_gc1 = ['a','b','c'] printed_gc1 = [] #Slice notation [:] can create a copy of the list. What is changed in the function is the copy, that is, the original list will not be changed in the function print_models(unprinted_gc1[:],printed_gc1) show(printed_gc1) print unprinted_gc1
Output is:
printing gc:c printing gc:b printing gc:a printed gc: c b a ['a', 'b', 'c']
7.5 passing any number of arguments
Example 1:
#1. Use position arguments in combination with any number of arguments def gc(number,*names): #When you don't know how many arguments there are, you can add * before the formal parameter, which allows python to create an empty tuple named names print "number:" + str(number) + " name:" for topping in names: print topping gc(1,'a') gc(3,'a','b','c')
Output is:
number:1 name: a number:3 name: a b c
Example 2:
#2. Use any number of keyword arguments def gc(first,last,**middle): #When you don't know how many arguments there are, you can add * * before the formal parameters, so that python can create an empty dictionary named names name = {} name['first name'] = first name['last name'] = last for key,value in middle.items(): name[key] = value return name full_name = gc('zhu ge','liang',zi='kong ming',hao='wo long') print full_name
Output is:
{'last name': 'liang', 'first name': 'zhu ge', 'zi': 'kong ming', 'hao': 'wo long'}
7.6 storing functions in modules
The module to be imported in this section is mokuai, and the specific code is:
#coding:gbk #Odd number between output a-b def Odd_number(a,b): number1 = 0 while number1 < a: number1 += 1 while a <= number1 < b: number1 += 1 if number1 % 2 == 0: continue print number1 #Name function def name1(first_name,last_name,middle_name=''): full_name1 = first_name + ' ' + middle_name + ' ' + last_name return full_name1.title() #Print model functions: def print_models(unprinted_gc,printed_gc): while unprinted_gc: current_gc = unprinted_gc.pop() #Send unprinted list into list loop print "printing gc:" + current_gc printed_gc.append(current_gc) #Send the printed content to the printed list
Example 1:
#1. Import the whole module import mokuai mokuai.Odd_number(2,8) a = mokuai.name1('gao','chi') print a
Output is:
3 5 7 Gao Chi
Example 2:
#2. Import specific functions #The import syntax is: from module name import function name #Multiple functions are: from module name, import function name 1, function name 2 from mokuai import Odd_number,print_models Odd_number(2,8) unprinted_gc0 = ['a','b','c'] printed_gc0 = [] print_models(unprinted_gc0,printed_gc0)
Output is:
3 5 7 printing gc:c printing gc:b printing gc:a
Example 3:
#3. Use as to assign alias to the function: from module name import function name as function alias from mokuai import Odd_number as on on(2,8)
Example 4:
#4. Use as to assign an alias to the module: import module name as module alias import mokuai as mk mk.Odd_number(2,8)
Example 5:
#5. Import all functions in the module: use * to import all functions from mokuai import * Odd_number(2,8) a = name1('gao','chi') print a unprinted_gc0 = ['a','b','c'] printed_gc0 = [] print_models(unprinted_gc0,printed_gc0)
Output is:
3 5 7 Gao Chi printing gc:c printing gc:b printing gc:a
8. Class
8.1 creating and using classes
Example 1:
#1. Create class class Dog(object): #Create Dog class def __init__(self,name,age): #Initialize the properties name and age self.name = name self.age = age def sit(self): print self.name.title() + "is now sitting." #Simulate a dog squatting when ordered def roll_over(self): print self.name.title() + "rolled over !" #Simulate the dog rolling when ordered
Note: we call the functions in the class methods__ init__ () used to initialize the instantiated object; Subclasses may not be overridden__ init__, When instantiating a subclass, the defined in the parent class will be called automatically__ init__.
Example 2:
#2. Create instances based on classes my_dog = Dog('willie',6) print "dog name:" + my_dog.name.title() #Accessing properties in the dog class print "dog age:" + str(my_dog.age) print ("\n") my_dog.sit() #Calling a method in a class my_dog.roll_over() print ("\n")
Output is:
Willie is now sitting. Willie rolled over !
Example 3:
my_dog = Dog('willie',6) your_dog = Dog('lucy',3) print "my dog name:" + my_dog.name.title() + " my dog age:" + str(my_dog.age) print "your dog name:" + your_dog.name.title() + " your dog age:" + str(your_dog.age) my_dog.sit() your_dog.roll_over()
Output is:
my dog name:Willie my dog age:6 your dog name:Lucy your dog age:3 Willie is now sitting. Lucy rolled over !
8.2 use classes and instances
Example 1:
#1. Add default values to attributes class Car0(object): def __init__(self,make,model,year): #Initialize properties self.make = make self.model = model self.year = year self.odometer_reading = 0 #Add a new attribute mileage with an initial value of 0 def get_describe_name(self): #Add description method long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print "mileage:" + str(self.odometer_reading) my_new_car = Car0('aodi','a4','2021') print my_new_car.get_describe_name() my_new_car.read_odometer() #2. Modify attribute value my_new_car.odometer_reading = 12 #(1) Method 1: directly modify the value of the attribute my_new_car.read_odometer()
Output is:
2021 Aodi A4 mileage:0 mileage:12
Example 2:
#(2) Method 2: modify the attribute value through the method class Car1(object): def __init__(self,make,model,year): #Initialize properties self.make = make self.model = model self.year = year self.odometer_reading = 0 #Add a new attribute mileage with an initial value of 0 def get_describe_name(self): #Add description method long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): #Display mileage print "mileage:" + str(self.odometer_reading) def update_odometer(self,mileage): #Add or modify methods for specified mileage self.odometer_reading = mileage def increament_odometer(self,miles): #Adding mileage increases the specified value self.odometer_reading += miles my_new_car = Car1('aodi','a4','2021') print my_new_car.get_describe_name() my_new_car.update_odometer(23500) my_new_car.read_odometer() my_new_car.increament_odometer(300) my_new_car.read_odometer()
Output is:
2021 Aodi A4 mileage:23500 mileage:23800
8.3 succession
For example:
#Inheritance (child and parent) class Car(object): def __init__(self,make,model,year): #Initialize properties self.make = make self.model = model self.year = year self.odometer_reading = 0 #Add a new attribute mileage with an initial value of 0 def get_describe_name(self): #Add description method long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print "mileage:" + str(self.odometer_reading) def update_odometer(self,mileage): #Add or modify methods for specified mileage if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print "you can't roll back an odometer" self.odometer_reading = mileage def increament_odometer(self,miles): #Adding mileage increases the specified value self.odometer_reading += miles class battery(): def __init__(self,battery_capacity=70): #Many battery attributes for electric vehicles can be extracted separately to form a battery class self.battery_capacity = battery_capacity def get_range(self): #New method for obtaining endurance mileage related to battery capacity if self.battery_capacity == 70: range = 240 elif self.battery_capacity ==85: range = 270 message = "range:" + str(range) print message def describe_battery(self): print "battery capacity:" + str(self.battery_capacity) + "KWh" class ElecticCar1(Car): #Add subcategory electric vehicle def __init__(self,make,model,year): #Initialize parent class properties # Use the super function to make the subclass instance contain all the attributes of the parent class, so the parent class is also called super class. In addition, the method used in Python 3 is super__ init__ () super(ElecticCar1, self).__init__(make,model,year) self.battery = battery() self.maximum_speed = 80 #Add subclass properties and set initial values def describe_maximum_speed(self): #Methods for adding subclasses print "maximum_speed:" + str(self.maximum_speed) + "Km/h" my_tesla = ElecticCar1('tesla','model s','2021') print my_tesla.get_describe_name() my_tesla.describe_maximum_speed() my_tesla.battery.describe_battery() my_tesla.battery.get_range()
Output is:
2021 Tesla Model S maximum_speed:80Km/h battery capacity:70KWh range:240
8.4 import class
The known module is car module, and the code is as follows:
#coding:gbk class Car(object): def __init__(self,make,model,year): #Initialize properties self.make = make self.model = model self.year = year self.odometer_reading = 0 #Add a new attribute mileage with an initial value of 0 def get_describe_name(self): #Add description method long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print "mileage:" + str(self.odometer_reading) def update_odometer(self,mileage): #Add or modify methods for specified mileage if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print "you can't roll back an odometer" self.odometer_reading = mileage def increament_odometer(self,miles): #Adding mileage increases the specified value self.odometer_reading += miles class battery(): def __init__(self,battery_capacity=70): #Many battery attributes for electric vehicles can be extracted separately to form a battery class self.battery_capacity = battery_capacity def get_range(self): #New method for obtaining endurance mileage related to battery capacity if self.battery_capacity == 70: range = 240 elif self.battery_capacity ==85: range = 270 message = "range:" + str(range) print message def describe_battery(self): print "battery capacity:" + str(self.battery_capacity) + "KWh" class ElecticCar1(Car): #Add subcategory electric vehicle def __init__(self,make,model,year): #Initialize parent class properties # Use the super function to make the subclass instance contain all the attributes of the parent class, so the parent class is also called super class. In addition, the method used in Python 3 is super__ init__ () super(ElecticCar1, self).__init__(make,model,year) self.battery = battery() self.maximum_speed = 80 #Add subclass properties and set initial values def describe_maximum_speed(self): #Methods for adding subclasses print "maximum_speed:" + str(self.maximum_speed) + "Km/h"
Example 1 importing a single class:
#1. Import a single class from car import Car my_new_car = Car('aodi','a4','2020') print my_new_car.get_describe_name() my_new_car.odometer_reading = 23 my_new_car.read_odometer()
Output is:
2020 Aodi A4 mileage:23
Example 2 importing multiple classes from a module:
#2. Import multiple classes from one module from car import Car,ElecticCar1 my_beetle = Car('gc','a1','2022') print my_beetle.get_describe_name() my_tesla = ElecticCar1('tesla','roadster','2022') print my_tesla.get_describe_name()
Output is:
2022 Gc A1 2022 Tesla Roadster
Example 3 Import the entire module:
import car my_beetle = car.Car('gc','a1','2022') #Use the module The syntax of class () accesses the required class print my_beetle.get_describe_name() my_tesla = car.ElecticCar1('tesla','roadster','2022') print my_tesla.get_describe_name()
Example 4 import all classes in the module (this import method is not recommended):
from car import * my_beetle = Car('gc','a1','2022') print my_beetle.get_describe_name() my_tesla = ElecticCar1('tesla','roadster','2022') print my_tesla.get_describe_name()