python基础知识D

变量数据类型注释

rand_var:int = 7
print(rand_var,type(rand_var))
rand_var = "7"
print(rand_var,type(rand_var))

"""【执行结果】
7 <class 'int'>
7 <class 'str'>
"""

注释本身不具备强制校验的功能,只是提示后续使用代码的人

1 多个类的管理

1.1 实例对象的方式

基础类

"""
模块文件名:base.py
"""
import time

class Base(object):

    首页 = ("xpath","//*[@id='query']")

    def __init__(self):
        self.driver = "webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)"

    def find_element(self):
        print(f"driver.find_element_by_xpath('{Base.首页[1]}')")

    @staticmethod
    def log():
        print(f"{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}\t驱动创建完成")

调用入口的类

from base import Base

class Entrance(object):

    def __init__(self):
        self.device_1 = Base()  # 设备1
        self.device_2 = Base()  # 设备2

        
ent = Entrance()

测试用例

"""
模块文件名:testcase.py
"""
from entrance import ent

# 调用属性
print("设备1",ent.device_1.首页)
print("设备1",ent.device_1.driver)
print("设备2",ent.device_2.首页)
print("设备2",ent.device_2.driver)

# 调用方法
ent.device_1.find_element()
ent.device_1.log()
ent.device_2.find_element()
ent.device_2.log()

1.2 类对象的方式

问题1:无法调用实例属性实例方法

问题2:实例对象作为全局变量,在代码执行完毕后,会从内存中销毁

2 初始化方法的继承

正常的继承

"""
模块文件名:simple_inherit.py
"""
class Father:

    def __init__(self,name,age):
        self.name = name
        self.age = age

class Son(Father):
    pass

print(Son("法外狂徒张三",18).name)
print(Son("法外狂徒张三",18).age)

继承时扩展

"""
模块文件名:simple_inherit.py
"""
class Father:

    def __init__(self,name,age):
        self.name = name
        self.age = age

class Son(Father):

    def __init__(self,name,age,fight_capa):
        super(Son, self).__init__(name,age)
        self.fight_capa = f"战斗力:{fight_capa}"

ZS = Son("法外狂徒李四",30,1000)
print(ZS.fight_capa)
print(ZS.name)
print(ZS.age)

扩展被继承

"""
模块文件名:simple_inherit.py
"""
class Father:

    def __init__(self,name,age):
        self.name = name
        self.age = age


class Son(Father):

    def __init__(self,name,age,fight_capa):
        super(Son, self).__init__(name,age)
        self.fight_capa = f"战斗力:{fight_capa}"


class GrandSon(Son):
    pass


ZWJ = GrandSon("张无忌",25,10000)
print(ZWJ.name,"\t",ZWJ.fight_capa)

多继承

print(GrandSon.__mro__)
"""【执行结果】
(<class '__main__.GrandSon'>, <class '__main__.Son'>, <class '__main__.Father'>, <class 'object'>)
"""

3 Python代码的简洁写法

if语句

一般写法

def judge(judge_num):
    if judge_num == 1:
        print("明天我要学习自动化")
    else:
        print("明天我要和队友刷副本")
judge(1)
judge(0)

简洁写法

judge = lambda judge_num:print("明天我要{}".format('学习自动化' if judge_num == 1 else '和队友刷副本'))
judge(1)
judge(0)

for语句

一般写法

# 获取0~100的偶数,以以列表返回
list1 = []
for i in range(100):
    if i % 2 == 0:
        list1.append(i)
print("list1= ",list1)

简洁写法

# 获取0~100的奇数,以以列表返回
list2 = [i for i in range(100) if i %2 != 0]
print("list2= ",list2)

混合使用

# 九九乘法表
list2 = [f"{i}x{j}={i*j}" for i in range(1, 10) for j in range(1, 10) if j <= i]
print(list2)

4 匿名函数

# 结构
lambda 参数:函数体
# 1 lambda函数赋值给变量
add = lambda x, y: x + y
print(add(2, 3))

# 2 覆盖原函数功能
add = lambda x, y, z: x + y + z
print(add(2, 3, 5))

# 3  作为其他函数的返回值
# pass

# 4 lambda函数作为参数
# 0~100不能被2整除,能被3整除的数,返回列表
print(list(filter((lambda x: x % 2 != 0 and x % 3 == 0), [i for i in range(100)])))

"""【执行结果】
[3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
"""

5 时区计算

import datetime

def time_calc(old_timezone:int,cur_timezone:int):
    time_diff = abs(cur_timezone - old_timezone)*3600  # 计算时差
    cur_time = datetime.datetime.now()  # 获取当前时间
    if cur_timezone > old_timezone:
        modify_time = cur_time + datetime.timedelta(seconds=time_diff)
        print(modify_time)
    elif cur_timezone < old_timezone:
        modify_time = cur_time + datetime.timedelta(seconds=-time_diff)
        print(modify_time)
    else:
        print(cur_time)

time_calc(-3,+8)
time_calc(-2,-9)
time_calc(0,0)

"""【执行结果】
2022-04-10 02:59:42.784507
2022-04-09 08:59:42.785496
2022-04-09 15:59:42.785496
"""

6 显式等待

import datetime
import time

def wait_element(element, interval=0.5, timeout=10):
    """
    功能:显示等待
    :param element:定位语句,比如:driver.find_element_by_id("...")
    :param interval:float 检查间隔时间
    :param timeout:int  最大加载时长
    :return:
    """
    spend_time = 0
    start_time = time.time()
    while spend_time < timeout:
        try:
            element
        except:
            end_time = time.time()
            spend_time = start_time - end_time
            time.sleep(interval)  # 操作间隔
            continue
        else:
            print(datetime.datetime.now(),"\t已经找到元素")
            return True
    print(datetime.datetime.now(),"\t不存在该元素")
    return False
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值