# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                       #
#               人生苦短    我学PYTHON                        #
#                                                       #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #

类、

# 带参构造方法
# 类中的构造方法,可以定义形式参数,目的是在创建对象的同时,为对象的实例属性赋值class Dog:def __init__(self, name, age):self.age = ageself.name = name# self关键字:类中定义的普通方法,默认第一个参数就是self,self表示的是当前的对象
# shout方法中调用了self.name和self.age,那么这个self表示的是当前调用shout()方法的对象
class Dog1:def __init__(self, name, age):self.age = ageself.name = namedef shout(self):print(self.name, self.age)# 换一个思路理解
# 在下面,创建的dog这个对象调用了shout()方法,那么此时self指代的就是dog这个对象
dog = Dog1("阿黄", 9)
print(dog.age)
print(dog.name)
dog.shout()# 类属性可以通过【类.属性=新的值】去修改类属性值,但是对象属性只能使用,不能修改
class Chinese:country = "中国"def __init__(self):passchi = Chinese()
chi.country = "韩国"
print(chi.country)  # 输出【韩国】
print(Chinese.country)  # 输出【中国】Chinese.country = "日本"
print(Chinese.country)  # 输出【日本】# 实例属性、实例方法
class Dog2:def __init__(self, name, age):self.age = ageself.name = namedef shout(self):# 实例方法中,可以通过self调用实例属性print(self.name, self.age)def talk_lif(self):# 实例方法中,也可以通过self调用实例方法self.shout()# 类方法:如果方法中,不需要调用任何的实例属性或实例方法,但是需要调用类属性,这时可以将这个方法定义成类方法。
# 定义类方法,需要在方法名上加上装饰器@classmethod
# 调用类方法时,应该通过类名或者对象直接调用
# 静态方法:如果方法中既不调用实例属性或方法,也不调用类属性或方法,那么这个方法应该定义成静态方法。
# @staticmethod静态方法可以直接通过类名或者对象调用

封装、

# 面向对象的三大特征:封装、继承、多态
# 封装有两层含义:
# (1) 将代码都写在类中,用类包装了代码。
# (2) 将类中的内容通过一些手段隐藏起来,从而保护代码的安全性。
# 注意:
# 1) 在类中双下划线开头的变量是私有变量
# 2) 在类中双下划线开头的方法是私有方法
# 3) 私有方法和私有变量只能在当前类调用,原则上不能再类外直接调用
# 4) 一旦我们把某个变量私有化,通常会为这个变量定义两个方法,一个是set_变量名()用来为这个变量赋值,一个get_变量名()用来获取变量的值。class Dog:def __init__(self,name,age):#用双下划线定义的实例属性属于私有属性,原则上只能在当前类中直接调用。self.__name = nameself.__age = agedef shout(self):print("狗的年龄是%d,狗的名字是%s"%(self.__age,self.__name))#__age是私有属性,所有要为age写一个set_age()方法,用来为age赋值def set_age(self,age):if age>0:self.__age = ageelse:print("输入的年龄有误,没有修改对象age的值")#也要为age写一个get_age()方法,用来获取age的值def get_age(self):return self.__agedef set_name(self,name):self.__name = namedef get_name(self):return self.__namedef __eat(self):print("我家的狗吃肉!")def dog_eat(self):self.__eat()dog = Dog("旺财",10)
print(dog.get_age())
dog.dog_eat()
#错误的演示,类外不能直接调用类的私有方法
dog.__eat()
#错误的演示,类外不能直接调用类的私有变量
print(dog.__age)
#当我们在类中把age私有化后,在类外直接对私有的内容访问,是不能访问的。
dog.__age = -10
dog.shout()

继承、

#    类与类之间为了代码的复用,可以把重复的内容放到父类(基类,超类)中去,然后用子类继承它。
#
#       Class 子类(父类,父类1,父类2………)
#           属性
#           方法
#
#   继承的特点:
#       (1) 子类继承父类所有的非私有的内容
#       (2) 子类可以扩展自己独有的内容
# 子类可以重写父类的方法,子类可以覆盖父类中同名的属性或方法,也就是子类的对象调用方法时,优先调用自己类中的内容。
class Student:def study(self):print("好好学习,天天向上!")class Little_student(Student):def play(self):print("小学生玩王者荣耀!")def study(self):print("学习思想品德!")# 子类中如果要调用父类的方法,可以通过super()来实现
class Student:def study(self):print("好好学习,天天向上!")class Little_student(Student):def play(self):print("小学生玩王者荣耀!")def study(self):# 在子类中可以通过super()来调用父类的方法super().study()print("学习思想品德!")

多态、

# 如果子类重写了父类的方法,那么调用重写后的方法具体执行什么内容,取决于当前调用方法的那个对象是谁。
# 多态的前提:类的继承、要有方法的重写
class Animal:def eat(self):print("动物吃")class Tiger(Animal):def eat(self):print("老虎吃肉!")
class Panda(Animal):def eat(self):print("熊猫吃竹子")
class Pig(Animal):def eat(self):print("猪吃草!")#定义一个形参,为了接收一个可以调用eat()方法的对象
def test_eat(x):x.eat()panda = Panda()
tiger2 = Tiger()
animal2 = Animal()
#根据传进来的对象不同,执行的方法也不同,这就是多态。
test_eat(panda)
test_eat(tiger2)
test_eat(animal2)print("---------------------------------")
amimal = Animal()
tiger = Tiger()
amimal.eat()
tiger.eat()

异常处理、

try:# 这里面写需要执行的代码a = 2b = "3"c = a + b
except TypeError: # 选写一个except就行了print("报错了会打印这条TypeError语句!")
except IndexError: # 选写一个except就行了print("报错了会打印这条IndexError语句!")
except: # 选写一个except就行了print("报错了会打印这条语句!")
else: # 可以省略这个模块print("如果没报错,会执行这条语句!")
finally: # 可以省略这个模块print("不管有没有报错,都会执行这条语句!")

FILE IO

IO表示input和output 是编程时对数据传输的一种描述,input表示输入数据,output表示输出数据。file = open("d:/file_io.txt","w") # w只写,r只读,a追加。file.write("hello 你好!\n") file.write(r"hello world!\n") # 如果在字符串前面加r,则表示后续的字符串所有内容都直接作为字符来处理,不再具备特殊含义。    file = open("./file_io.txt", "a")file.write("这是追加的内容!")file = open("./file_io.txt", "r") # 相对路径以当前代码文件为参考确认的路径。    content = file.read() # read()方法:从文件中将整个文件的所有数据都读出来。content = file.read(5) # 从文件中读取5个字符print(content, end="") # 如果不想换行打印,就可以在print()函数中指定end的值为空字符   content = file.readline() # 读取文件中的一行数据if len(content) == 0:breakprint(content, end="")file.close()

FILE IO_CSV

import csvclass CSV_write:def csv_write(self):# csv 的write# 打开/创建csv文件,可写模式,newline=""代表不跳过下一行file = open("csv_data_01.csv", "w", newline="")# 创建对象writewrite = csv.writer(file)# 写入csv表头,按照列表中的顺序,依次填入excel表格的第一行write.writerow(['序号', '标题', '公司', '薪资', '地点'])file.close()class CSV_read:def csv_read(self):with open('csv_data_01.csv', 'r') as f:reader = csv.reader(f)for row in reader:print(row)# 设计函数专门读取 csv文件
# 参数1 文件名 参数2: 读取第几行
def get_csv_data(csv_file,line):jw_csv_file= open(csv_file, 'r', encoding='utf-8-sig')# 打开文件reader = csv.reader(jw_csv_file) # 加载数据# 参数2 :决定了下标位置的开始计数方式,默认从0开始,可设置为从1开始for index, row in enumerate(reader, 1): # 枚举if index == line:print(row)return row
if __name__=="__main__":# 自测#参数1  当前的csv文件# 参数2   行数get_csv_data("./jwaccount.csv",2)

FILE IO_EXCEL

# # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# 能够操作Excel的模块:xlrd openpyxl pandas
# openpyxl三大对象:工作簿、工作表、单元格
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
import openpyxl
import osclass ExcelRead:def excel_read(self):# 工作簿EXCEL所在目录# os.path.dirname():得到上一级目录,os.getcwd():得到当前脚本的目录path = os.path.dirname(os.getcwd()) + "\\data_control\\" + "excel_data_01.xlsx"# 读取工作簿wk = openpyxl.load_workbook(path)# 读取工作表sheet = wk["Sheet1"]# 读取单元格的内容,存储至变量value中# value = sheet.cell(row=1, column=1).value# 获取单元格行数、列数rows = sheet.max_rowcols = sheet.max_column# 这里演示比较复杂的数据嵌套结构:通过字典、列表嵌套的方式保存数据        '''[{'username': 'test01', 'passwd': 10001},{'username': 'test02', 'passwd': 10002},{'username': 'test03', 'passwd': 10003},{'username': 'test04', 'passwd': 10004},{'username': 'test05', 'passwd': 10005},{'username': 'test06', 'passwd': 10006},{'username': 'test07', 'passwd': 10007},{'username': 'test08', 'passwd': 10008},{'username': 'test09', 'passwd': 10009},{'username': 'test10', 'passwd': 10010}]'''a=[]for x in range(2, rows + 1):dic = {}for y in range(1, cols + 1):dic[sheet.cell(row=1, column=y).value] = sheet.cell(row=x, column=y).valuea.append(dic)return a# qq = ExcelRead().excel_read()
# print(qq)

FILE IO_TXT

# 读取数据到列表b
file_path = "./txt_data_01.txt"
b = []
file = open(file_path, 'r', encoding='UTF-8')
while True:content = file.readline()b.append(content)if len(content) == 0:break
file.close()# 记录行数
lines = 0
filename = open(file_path, 'r', encoding='UTF-8')  # 以只读方式打开文件
file_contents = filename.read()  # 读取文档内容到file_contents
for file_content in file_contents:  # 统计文件内容中换行符的数目if file_content == '\n':lines += 1
if file_contents[-1] != '\n':  # 当文件最后一个字符不为换行符时,行数+1lines += 1
file.close()# 写入b列表数据
output_path = "./output_txt.txt"
file_02 = open(output_path, "w", encoding='UTF-8')
file_02.writelines(b)
file_02.close()

FILE IO_YAML

from appium import webdriver
import yaml
import os
#日志准备
def appium_desired():# 获取当前路径---就算被别的文件调用 获取当前位置base_dir = os.path.dirname(__file__)# os.path.dirname(__file__)  获取当前的配置文件# 拼接路径yaml_path = os.path.join(base_dir, 'jw_kyb_caps.yaml')print(yaml_path)jwfile=open(yaml_path,'r',encoding='utf-8')# 打开配置文件data=yaml.load(jwfile)# 加载配置文件内容desired_caps={}# 利用data读取每个键对应的值desired_caps['platformName']=data['platformName']desired_caps['platformVersion']=data['platformVersion']desired_caps['deviceName']=data['deviceName']#os.path.dirname代表获取当前路径  比如  c:/a/b/c.txt ====>c:/a/b/# 两层的话再获取上一层路径base_dir = os.path.dirname(os.path.dirname(__file__))print("项目路径",base_dir)# 读取到了 被测试app的路径和软件名称# join拼接路径app_path = os.path.join(base_dir,'app', data['appname'])desired_caps['app']=app_pathdesired_caps['appPackage']=data['appPackage']desired_caps['appActivity']=data['appActivity']desired_caps['noReset']=data['noReset']driver=webdriver.Remote('http://'+str(data['ip'])+':'+str(data['port'])+'/wd/hub',desired_caps)driver.implicitly_wait(4)return driver # 根据配置文件的出需要控制的手机和app
# 单元测试===》自测一下
if __name__ == '__main__':appium_desired()

数据驱动_DDT

import unittest
from ddt import ddt, data, unpack# 定义一个列表,列表数据为多个字典,字典数据为键值对存储具体数据。
dic = [{"name":"zhangsan", "age":25},{"name":"lisi", "age":24}, {"name":"wangwu", "age":18}]@ddt
class MyTestCase(unittest.TestCase):def setUp(self) -> None:print("开始测试~~~")@data(*dic)@unpackdef test_01(self, name, age):print(name, age)def tearDown(self) -> None:print("结束测试~~~")if __name__ == '__main__':unittest.main()

数据驱动案例_EXCEL+DDT

# # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# 能够操作Excel的模块:xlrd openpyxl pandas
# openpyxl三大对象:工作簿、工作表、单元格
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
import openpyxl
import os
from prettytable import PrettyTableclass ExcelRead:def excel_read(self):# Excel路径# path = os.path.dirname(os.getcwd()) + "\\demo\\" + "price.xlsx"path = "./price.xlsx"# 读取工作簿wk = openpyxl.load_workbook(path)# 读取工作表sheet = wk["Sheet1"]# 读取单元格的内容,存储至变量value中# value = sheet.cell(row=1, column=1).value# 获取单元格行数、列数global rowsglobal colsrows = sheet.max_rowcols = sheet.max_column# 记录表头信息到列表headglobal headhead = []for h in range(1, cols + 1):header = sheet.cell(row=1, column=h).valuehead.append(header)# 记录表内容到contentglobal contentcontent = []for x in range(2, rows + 1):dic = {}for y in range(1, cols + 1):dic[head[y-1]] = sheet.cell(row=x, column=y).valuecontent.append(dic)return contentExcelRead().excel_read()
while True:find = input("请输入要查询的商品:")# 写入表头内容,表头为列表headx = PrettyTable(head)# nn指向字典中的第二个数据的【键】,即"存货名称"nn = head[1]# content为一个列表,里面嵌套很多字典,字典里面为数据# 从content的第一行开始遍历for i in range(1, rows-1):# p指向列表的第i个字典p = content[i]# p[nn] 代表取nn键对应的值,(键值对的值,nn为【键】),输入的数据find用来匹配nn键对应的值,这里直接用p["存货名称"]if find in p["存货名称"]:m = []for o in range(0, cols):q = head[o]n = p[q]m.append(n)x.add_row(m)# 全体左对齐 x.align[] = "l"for g in range(0,cols):aa = head[g]x.align[aa] = "l"print(x)

Python学习笔记:Python基础使用相关推荐

  1. Python学习笔记_1_基础_2:数据运算、bytes数据类型、.pyc文件(什么鬼)

    Python学习笔记_1_基础_2:数据运算.bytes数据类型..pyc文件(什么鬼) 一.数据运算 Python数据运算感觉和C++,Java没有太大的差异,百度一大堆,这里就不想写了.比较有意思 ...

  2. python笔记基础-Python学习笔记(基础)

    python基础学习笔记.语法.函数等. 基础定义utf-8文件头#!/usr/bin/env python3 # -*- coding: utf-8 -*- 2.循环// name是值 names是 ...

  3. python 学习笔记(基础输入输出,字符串,循环,三种数组)

    学习python发现这门语言和其他语言有很多不同之处,比如python的变量不需要要声明类型,python是解释性语言所以要注意函数定义的位置,python注重代码格式而不注重符号.python方便得 ...

  4. Python学习笔记——Python和基础知识

    Python优缺点 优点 简单----Python是一种代表简单主义思想的语言.阅读一个良好的Python程序就感觉像是在读英语一样,尽管这个英语的要求非常严格!Python的这种伪代码本质是它最大的 ...

  5. Python学习笔记----入门基础

    第一章 Python入门基础 第一节 优雅的Python 一.Python的基本介绍 (1)Python是程序设计语言 1.自然语言 2.机器语言 3.程序设计语言 ①由文字组成的文本文件, ②程序设 ...

  6. python学习笔记:基础语法

    目录 python语言概述 python基础语法 python标准数据类型 1.数字类型 2.字符串类型 3.列表类型 4.元组 5.字典 python基础语法 1.条件判断语句 2.循环语句 3.函 ...

  7. Python学习笔记 - Python语法基础

    前言 本篇博文主要介绍Python中的一些最基础的语法,其中包括标识符.关键字.内置函数.变量.常量.表达式.语句.注释.模块和包等内容. 一.标识符.关键字和内置函数 任何一种语言都离不开标识符和关 ...

  8. Python学习笔记--Python字符串连接方法总结

    声明: 这些总结的学习笔记,一部分是自己在工作学习中总结,一部分是收集网络中的知识点总结而成的,但不到原文链接.如果有侵权,请知会,多谢. python中有很多字符串连接方式,总结一下: 1)最原始的 ...

  9. Python学习笔记 - Python语言概述和开发环境

    一.Python简介 1.1  Python语言简史 Python由荷兰人吉多·范罗苏姆(Guido van Rossum)于1989年圣诞节期间,在阿姆斯特丹,为了打发圣诞节的无聊时间,决心开发一门 ...

  10. (转载)[python学习笔记]Python语言程序设计(北理工 嵩天)

    作者:九命猫幺 博客出处:http://www.cnblogs.com/yongestcat/ 欢迎转载,转载请标明出处. 如果你觉得本文还不错,对你的学习带来了些许帮助,请帮忙点击右下角的推荐 阅读 ...

最新文章

  1. Spring MVC 过时了吗?
  2. linux 读书笔记
  3. html页面vertical,vertical.html
  4. 长春理工大学第十四届程序设计竞赛
  5. Android项目开发实战—自定义左右菜单
  6. 怎么在电脑安装php文件夹在哪个文件夹,php进行文件上传时找不到临时文件夹怎么办,电脑自动保存的文件在哪里...
  7. angular和JAVA实现aes、rsa加密解密,前后端交互,前端加解密和后端JAVA加解密实现
  8. Sublime Text3(mac)一些插件和快捷键
  9. Jmeter BeanShell采样器提取接口响应写入csv文件(四)
  10. python tk combobox设置值为空_Python编程从入门到实践日记Day24
  11. Python 机器学习:多元线性回归
  12. unix 时间戳转化为 日期格式
  13. 关于保利威视平台的API调用签名
  14. 机器人学笔记之——空间描述和变换:姿态的其他描述方法
  15. rj45插座尺寸图_RJ45网络插座的基本知识
  16. 微信小程序显示天气预报
  17. oracle数据库exp备份表,oracle数据库exp备份表
  18. eclipse的工作空间如何复制
  19. 美国2012政治献金数据分析(附有源数据和题目)
  20. 前端开源实战项目,大厂级别

热门文章

  1. netty基础教程-3、helloworld(cs模式)
  2. grpc、https、oauth2等认证专栏实战17:grpc-go自定义认证之base64验证介绍
  3. 刘銮雄-公道不在人心,是非只在时势
  4. 中国重晶石采矿产业“十四五”投资规划及前景动态分析报告2022年版
  5. 1-SIM卡复位ATR解析
  6. 通信系统原理[郭宇春]——信号与噪声——课后习题答案
  7. PMP就是个垃圾证书,YES or NO
  8. ps制作双重曝光海报
  9. c语言如何乘分数,C语言分数相乘程序简化问题。
  10. Mac M1安装fish shell 遇见的坑