zoukankan      html  css  js  c++  java
  • Python+Selenium进阶版(二)- Python中类/函数/模块的简单介绍

      关于Python中类和函数及方法的调用,我们写在这个demo.py文件,具体代码如下:

    # coding = utf-8
    
    class ClassA(object):
        string1 = "这是一个字符串。"
    
        def insteancefunc(self):
            print('这是一个实例方法。')
            print(self)
    
        @classmethod
        def classfunc(cls):
            print('这是一个类方法。')
            print(cls)
    
        @staticmethod
        def staticfun():
            print('这是一个静态方法。')
    
    test = ClassA #初始化一个ClassA的对象,test是类ClassA的实例对象
    print('1')
    test.insteancefunc(test) #对象调用实例方法
    print('2')
    test.staticfun() #对象调用静态方法
    print('3')
    test.classfunc() #对象调用类方法
    print('4')
    print(test.string1)
    print('5')
    ClassA.insteancefunc(test) #类调用实例方法,需要带参数,这里的test是一个对象参数
    print('6')
    ClassA.insteancefunc(ClassA) #类调用实例方法,需要带参数,这里的ClassA是一个类参数
    print('7')
    ClassA.staticfun() #类调用静态方法
    print('8')
    ClassA.classfunc() #类调用类方法
    

      

    一、类的定义,class开头的就表示这是一个类,小括号里面的,表示这个类的父类,涉及到继承,默认object是所有类的父类。python中定义类,小括号内主要有三种:1.具有一个父类;2.object;3.空白;

    二、函数或方法的定义,def开头就表示定义一个函数,方法包括,实例方法,类方法,静态方法,注意看类方法和静态方法定义的时候上面有一个@标记。

    三、对象调用方法和类调用方法的使用。

    练习场景:百度搜索

    具体代码:

    # coding=utf-8
    import time
    from selenium import webdriver
    
    class BaiduSearch(object):
        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.implicitly_wait(10)
    
        def open_baidu(self):
            self.driver.get("https://www.baidu.com")
            time.sleep(1)
    
        def test_search(self):
            self.driver.find_element_by_id('kw').send_keys("selenium")
            time.sleep(1)
            print(self.driver.title)
            try:
                assert 'selenium' in self.driver.title
                print('Test pass.')
            except Exception as e:
                print('Test fail.')
            self.driver.quit()
    
    baidu = BaiduSearch()
    baidu.open_baidu()
    baidu.test_search()
    

      

    参考文章:https://blog.csdn.net/u011541946/article/details/70157011

  • 相关阅读:
    Kth Largest Element in an Array -- LeetCode
    First Missing Positive -- LeetCode
    Path Sum II (Find Path in Tree) -- LeetCode
    Email List
    Divide Two Integers -- LeetCode
    Delete Node in a Linked List
    Compare Version Numbers -- LeetCode
    Broken Code
    Trapping Rain Water (Bar Height) -- LeetCode
    Count and Say (Array Length Encoding) -- LeetCode
  • 原文地址:https://www.cnblogs.com/zhaocbbb/p/12657755.html
Copyright © 2011-2022 走看看