Chapter 7 Functions and Methods

A function is an organized, reusable piece of code that implements a single, or related function.


定义一个函数
1.函数代码块以def关键词开头,后接函数标识名和圆括号()。
2.任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
3.函数的第一行语句可以选择性地使用文档字符串-用于存放函数说明。
4.函数内容以冒号起始,并且缩进。
5.return[表达式]结束函数,选择性地返回一个值给调用方,不带表达式的return相当于返回None

View all built-in functions, the commonly used built-in functions are in the blue box.
write picture description here
View help information: >>>help(len)
You can fill in any built-in functions you need in the brackets.

  • custom function
#coding=utf-8
def eat():
    n="牛吃草"
    return n
print(eat())
#没有return打印出来是None

Login case

#coding=utf-8
from selenium import webdriver
import time
#登录函数
def denglu(driver,username,password):
    #点击登录
    driver.find_element_by_xpath(".//*[@id='app']/div[1]/div[5]/div[2]/div[1]/span[1]").click()
    #输入用户名
    driver.find_element_by_xpath(".//*[@id='app']/div[1]/div[1]/div/input[1]").send_keys(username)
    #输入密码
    driver.find_element_by_xpath(".//*[@id='app']/div[1]/div[1]/div/input[2]").send_keys(password)
    #点击确认登录
    driver.find_element_by_xpath(".//*[@id='app']/div[1]/div[1]/div/div[3]").click()
    time.sleep(2)
    #获取用户名
    result = driver.find_element_by_xpath(".//*[@id='app']/div[1]/div[5]/div[2]/div[2]/span[2]").text
    return result

if __name__=="__main__":
    driver=webdriver.Firefox()
    driver.get("http://www.tianguiedu.com/")
    username="xxxxxxxxxxx"
    password="xxxxxx"
    time.sleep(3)
    print(denglu(driver,username,password))
  • Classes and methods (a class is an abstract concept, like a human being, there is no concrete thing)
#coding=utf-8
class All():
#方法一
    def add(self):
        print("哈哈")
##方法二
    def acc(self):
        return True
##方法三
    def aee(self,a,b):
        return a+b
#方法四
    def aff(self,a=1,b=2):
        return a+b
if __name__=="__main__":
    a=All().add()
    b=All().acc()
    c=All().aee(1,2)
    d=All().aff()
    print(a)
    print(b)
    print(c)
    print(d)
  • Inheritance
    Inheritance means that the subclass inherits the parent class. After inheritance, the subclass also has the methods of the parent class.
#coding=utf-8
class Father():
    def home(self):
        print("这是父亲的房子")
    def car(self):
        print("这是父亲的宾利")
class Mother():
    def company(self):
        print("这是母亲的公司")
class Son(Father,Mother):#儿子继承父母的财产
    def caichan(self):
        self.home()
        self.car()
        self.company()
if __name__=="__main__":
    a=Son()
    a.caichan()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324572262&siteId=291194637