Python入门到放弃系列三

目录

 

 第一部分 基础知识

第九章 类

第十章 文件和异常

文件的写入信息

异常处理:try-catch.py

文件不存在异常:(file-not-found.txt)

文本分析,测试分割

Json模块存储数据  json-write.py

第十一章 测试代码


 第一部分 基础知识

第九章 类

 

在面向对象里面 类是必不可少的,抽象出来一个大类,利于划分、管理、扩展等,高内聚,低耦合的思想。一般抽象出来独立的功能类,可以到处copy。

和java思想的方式差不多,直接写代码。

编写  cls.py

class Dog(object):
    """docstring for  Dog"""

    def __init__(self, name, age):  # 初始构造器  ,self ?每个方法都必须的吗?
        self.name = name
        self.age = age
        self.abc = 0  # 默认值直接设置

    def sit(self):
        print('dog sit:'+self.name.title()+',age:'+str(self.age))


jinmao = Dog('dajinmao', '10')  # 构造对象
jinmao.sit()
taidi = Dog('taidi', '5')  # 构造多个实例对象
taidi.sit()
taidi.abc = 10  # 修改属性
taidi.age = 8  # 修改属性
print(taidi.abc)
print(taidi.age)

输出:

dog sit:Dajinmao,age:10

dog sit:Taidi,age:5

10

8

[Finished in 0.0s]

extend.py (测试继承 和 导入模块)

class Car():
    """docstring for Car"""

    def __init__(self, make, modle, year):  # 注意在2.7 中的语法是不同的。
        self.make = make
        self.modle = modle
        self.year = year
        self.odometer = 0

    def get_desicriptive_name(self):
        long_name = str(self.year)+' '+self.make+' '+self.modle
        return long_name.title()

        def increaseNum(self):
            self.odometer += 1


"""  电动车 继承 汽车 """

class ElecticCar(Car):
    """docstring for ElecticCar"""

    def __init__(self, make, model, year):
        super().__init__(make, model, year)

    def increaseNum(self):  #重写父类的方法
        self.odometer += 2


my_tesla = ElecticCar('tesla', 'model s', 2021)  # 前头之前一直抱错,有个空格,这格式也是醉了,
my_tesla_name = my_tesla.get_desicriptive_name()
print(my_tesla_name)
my_tesla.increaseNum()
print(my_tesla.odometer)


from cls import Dog   #从cls文件引入 Dog类,也可以导入多个类,或者 *  类似方法导入,不再演示了。


keji = Dog('keji', '3')  # 构造多个实例对象
keji.sit()

输出:

2021 Tesla Model S

2

dog sit:Dajinmao,age:10

dog sit:Taidi,age:5

10

8

dog sit:Keji,age:3

[Finished in 0.0s]

忽然想到python如何多线程?和如何连数据库?等看完本书,再研究这个细节。先找了个https://www.runoob.com/python3/python-mysql-connector.html

第十章 文件和异常

文件的读取

with open('read_test.txt') as file_object:
    context = file_object.read()
    print("xx:"+context)  # 整个读出来的

file_path = 'data/filename.txt'
with open(file_path) as file_object:  
    for line in file_object: #逐行读出 
        print("BB:"+line.strip())  #如果不加strip会有换行符打印出空行显示

with open(file_path) as file_object:
    lines=file_object.readlines()

print("with代码块外使用:"+str(lines))

输出:

xx:test1

test2

test3

test4

test6

 

BB:read_test.txt

BB:sort.py

BB:untitled

BB:while.py

with代码块外使用:['read_test.txt\n', 'sort.py\n', 'untitled\n', 'while.py\n']

[Finished in 0.1s]

文件的写入信息

filename='programming.txt'

'''
#默认只读模式,也就是r,写的时候w, 如果文件存在?会覆盖的,一定要注意
#如果是追加内容的话,用 a  
'''
with open(filename,'w') as file_object:  
    file_object.write("I am  love programming!\n")
    file_object.write("I am  love programming2!\n")  #写入多行
    file_object.write("I am  love programming3!\n")

with open(filename,'a') as file_object:
    file_object.write("I am love append content!\n")
    file_object.write("I am love append content!\n")

with open(filename) as file_object:
    print(file_object.read())

输出:

I am  love programming!

I am  love programming2!

I am  love programming3!

I am love append content!

I am love append content!

 

[Finished in 0.0s]

异常处理:try-catch.py

# -*- coding: utf-8 -*
try:
    print(5/0)
except ZeroDivisionError:
    print('you can’t divide by zero!')


print('Give me two number,I‘ll divide them')
print('Enter ‘q’ to  end!')
while True:
    first = input('\n pls input first number:')
    if first == 'q':
        break
    second = input('\npls input second number:')
    try:
        answer = int(first)/int(second)
    except ZeroDivisionError:
        print('you cant divide by zero!')
    else:
        print('answer:'+str(answer))

输出:

文件不存在异常:(file-not-found.txt)

filename='abc.txt' #不存在的文件
with open(filename,'r') as file_object:
    print(file_object.readlines())

执行抱错

Traceback (most recent call last):

  File "/Users/ruishen/python_work/data/file-not-found.py", line 3, in <module>

    with open(filename,'r') as file_object:

FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

[Finished in 0.1s with exit code 1]

[cmd: ['/usr/local/bin/python3', '-u', '/Users/ruishen/python_work/data/file-not-found.py']]

[dir: /Users/ruishen/python_work/data]

[path: /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home//bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin::/Users/ruishen/apps/apache-maven-3.8.1/bin]

python日志输出:https://www.jianshu.com/p/9884a660050f

文本分析,测试分割

title='Alice in Wonderland!'
title2='Alice--in--Wonderland!'
print(title.split())
print(title.split().__len__())  #等同于 直接len(xxx)
print(title2.split('--')) #支持指定符号分割

输出:

['Alice', 'in', 'Wonderland!']

3

['Alice', 'in', 'Wonderland!']

[Finished in 0.0s]

Json模块存储数据  json-write.py

 

import json  # 引入json模块
numbers = [1, 3, 5, 8, 2]
filename = 'numbers.json'

with open(filename, 'w') as file_object:
    json.dump(numbers, file_object)  # 存储数据到numbers.json

with open(filename, 'r') as file_object:
    numbers2 = json.load(file_object)  #反向从文本里面读出后序列化到numbers2上

print(numbers)
print(numbers2)

输出:

[1, 3, 5, 8, 2]

[1, 3, 5, 8, 2]

[Finished in 0.1s]

第十一章 测试代码

本章主要讲了下单元测试的类库使用,各种语言都有对应的单元测试框架或者实现方式。像java中junit,jcoco还有一些springTest等框架

 

为简化流程,只学习核心使用方式测试方式写在一个文件了,(unit-test.py)

def get_name(first,last):
    return str(first+ " "+last).title()

import unittest
class NameTestCase(unittest.TestCase):
     
     def test_first_last_name(self):  #自定义单元测试类
         ret_name=get_name('tom','kelusi')
         self.assertEqual(ret_name,'Tom Kelusi')

unittest.main()  #执行入口,调用框架

执行成功的时候如下

若失败如下:

各种调用断言的方法:

接下来不写示例代码了,没意思,就是业务逻辑确定一个输入,自己调用某个类的某个方法来确定返回值一定是某一个值。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值