小甲鱼课程学习028-040

028文件:因为懂你,所以永恒

>>> f = open('E:\\zetianji.txt')
>>> f
<_io.TextIOWrapper name='E:\\zetianji.txt' mode='r' encoding='cp936'>
>>> #f.read()读取
>>> f.read(5)
'\n《择天记'
>>> f.tell()#返回当前文件中的位置
10
>>> lines = list(f)
>>> for each_line in lines:
    print(each_line)# 效率很低
>>> for each_line in f:
    print(each_line)#高效率
>>> f.write('I love you')
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    f.write('I love you')
io.UnsupportedOperation: not writable
>>> f = open('E:\\test.txt','w')
>>> f.write('我爱鱼C工作室')
7
>>> f.close()


029文件:一个任务

030文件系统:介绍一个高大上的东西

>>> import random
>>> secret = random.randint(1,10)
>>> secret
8
>>> import os
>>> os.getcwd()
'D:\\xiaojiayu'
>>> os.listdir('D:\\xiaojiayu')
['009_example1.py', '009_example2.py', '019_test1.py', '029test_1.py', '029test_2.py', 'boy_1.txt', 'boy_2.txt', 'boy_3.txt', 'fabnoncii.py', 'fabnoncii2.py', 'factorial.py', 'girl_1.txt', 'girl_2.txt', 'girl_3.txt', 'hanol.py', 'method1.py', 'method2.py', 'method3.py', 'record.txt', 'wordgame_1.py']
>>> os.system('clac')
1
>>> #打开计算机
>>> os.curdir#指代当前目录
'.'
>>> os.listdir(os.curdir)
['009_example1.py', '009_example2.py', '019_test1.py', '029test_1.py', '029test_2.py', 'boy_1.txt', 'boy_2.txt', 'boy_3.txt', 'fabnoncii.py', 'fabnoncii2.py', 'factorial.py', 'girl_1.txt', 'girl_2.txt', 'girl_3.txt', 'hanol.py', 'method1.py', 'method2.py', 'method3.py', 'record.txt', 'wordgame_1.py']
>>> os.name
'nt'
>>> os.path.basename('D:\\xiaojiayu')
'xiaojiayu'
>>> os.path.basename('D:\\xiaojiayu\\009_example2.py')#去掉路径,返回当前文件名
'009_example2.py'
>>> os.path.dirname('D:\\xiaojiayu\\009_example2.py')#去掉文件名,返回当前路径
'D:\\xiaojiayu'
>>> os.path.join('D:\\''A', 'B', 'c')#将path1、pah2组合为一个文件名
'D:\\A\\B\\c'
>>> os.path.split('D:\\xiaojiayu\\009_example2.py')#分离路径和文件名
('D:\\xiaojiayu', '009_example2.py')
>>> os.path.splitext('D:\\xiaojiayu\\009_example2.py')#分离文件名和扩展名
('D:\\xiaojiayu\\009_example2', '.py')
>>> os.path.getatime('D:\\xiaojiayu\\girl_2.txt')
1499653732.271157
>>> import time
>>> time.gmtime(os.path.getatime('D:\\xiaojiayu\\girl_2.txt'))
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=10, tm_hour=2, tm_min=28, tm_sec=52, tm_wday=0, tm_yday=191, tm_isdst=0)
>>> time.localtime(os.path.getatime('D:\\xiaojiayu\\girl_2.txt'))
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=10, tm_hour=10, tm_min=28, tm_sec=52, tm_wday=0, tm_yday=191, tm_isdst=0)

031永久存储:腌制一缸美味的泡菜

>>> import pickle
>>> my_list = [123, 3.14, '小甲鱼', ['another list']]
>>> pickle_file = open('my_list.pkl', 'wb')
>>> pickle.dump(my_list,pickle_file)
>>> pickle_file.close()
>>> pickle_file = open('my_list.pkl', 'rb')#打开
>>> my_list2 = pickle.load(pickle_file)
>>> print(my_list2)
[123, 3.14, '小甲鱼', ['another list']]

032异常处理:你不可能总是对的

>>> my_list = ['小甲鱼是帅哥']
>>> assert len(my_list)> 0
>>> my_list.pop()
'小甲鱼是帅哥'
>>> assert len(my_list)> 0 #assert断言语句失败
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    assert len(my_list)> 0 #assert断言语句失败
AssertionError
>>> 
>>> my_list = [1,2,3]
>>> my_list[2]
3
>>> my_list[3]
Traceback (most recent call last):
  File "<pyshell#62>", line 1, in <module>
    my_list[3]
IndexError: list index out of range
>>> my_dict = {'one':1,'two': 2, 'three': 3}
>>> my_dict['one']
1
>>> my_dict['four']
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    my_dict['four']
KeyError: 'four'
>>> my_dict.get('four')

033异常处理:你不可能总是对的2

try-except语句:

try:

    检测范围

except Exception[as reason]:

    出现异常后的处理代码

#f = open('我为什么是一个文件.txt')当这个txt不存在时,FileNotFoundError
#print(f.read())
#f.close()
try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError:
    print('文件出错啦!')


try:
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错啦!\n错误的原因是:' + str(reason))
文件出错啦!
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'

try:
    sum = 1 + '1'
    f = open('我为什么是一个文件.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('文件出错啦!\n错误的原因是:' + str(reason))
    
except TypeError as reason:
    print('类型出错啦!\n错误的原因是:' + str(reason))
#两个print error只打印最后一个!
类型出错啦!
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'

try-finally语句:

try:

    检测范围

except Exception[as reason]:

    出现异常后的处理代码

finally:

    无论如何都会被执行的代码

try:
    f = open('我为什么是一个文件.txt')
    print(f.write('我存在了!'))
    sum = 1 + '1'
    f.close()
except OSError as reason:
    print('文件出错啦!\n错误的原因是:' + str(reason))
    
except TypeError as reason:
    print('类型出错啦!\n错误的原因是:' + str(reason))
文件出错啦!
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'
try:
    f = open('我为什么是一个文件.txt','w')
    print(f.write('我存在了!'))
    sum = 1 + '1'
except OSError as reason:
    print('文件出错啦!\n错误的原因是:' + str(reason))
    
except TypeError as reason:
    print('类型出错啦!\n错误的原因是:' + str(reason))
finally:
    f.close() 
5
类型出错啦!
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'

raise语句

>>> 1/0
Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError('除数为零的异常')
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
    raise ZeroDivisionError('除数为零的异常')
ZeroDivisionError: 除数为零的异常
034 丰富的else和简洁的with语句

def showMaxFactor(num):
    count = num // 2
    while count > 1:
        if num % count == 0:
            print('%d最大的约数是%d' % (num,count))
            break
        count -= 1
    else:
        print('%d是素数!' % num)

num = int(input('请输入一个数:'))
showMaxFactor(num)

请输入一个数:11
11是素数!

try:
    int('abc')
except ValueError as reason:
    print('出错啦:' + str(reason))
出错啦:invalid literal for int() with base 10: 'abc'

try:
    print(int('123'))
except ValueError as reason:
    print('出错啦:' + str(reason))
else:
    print('没有任何异常!')
123
没有任何异常!

with语句

try:
    f = open('data.txt', 'w')
    for each_line in f:
        print(each_line)
except OSError as reason:
    print('出错啦:' + str(reason))
finally:
    f.close()
出错啦:not readable
try:
    with open('data.txt', 'w') as f:
        for each_line in f:
            print(each_line)
except OSError as reason:
    print('出错啦:' + str(reason))
出错啦:not readable


035图形用户界面入门:EasyGui


036 类和对象:给大家介绍对象

        对象=属性【静态】+方法【动态】

class Turtle:# Python中的类名约定以大写字母开头
    """关于类的一个简单例子"""
    #属性
    color = 'green'
    weight = 10
    legs = 4
    shell = True
    mouth = '大腿'
    #方法
    def climb(self):
        print('我正在很努力的向前爬。。。')

    def run(self):
        print('我正在飞快的向前跑。。。')

    def bite(self):
        print('咬死你咬死你!')

    def eat(self):
        print('有的吃,真满足')

    def sleep(self):
        print('困了,睡了,晚安,Zzzz')
>>> tt = Turtle()
>>> Turtle()
<__main__.Turtle object at 0x0213D0F0>
>>> tt.climb()
我正在很努力的向前爬。。。
>>> tt.bite()
咬死你咬死你!
>>> tt.sleep()
困了,睡了,晚安,Zzzz
>>> 
oo的特征:Object Oriented面向对象

>>> list1 = [2, 1, 7, 5, 3]
>>> list1.sort()
>>> list1
[1, 2, 3, 5, 7]
>>> list1.append(9)
>>> list1
[1, 2, 3, 5, 7, 9]
>>> #第一点封装、第二点继承
>>> class MyList(list):
	pass

>>> list2 = MyList()
>>> list2.append(5)
>>> list2.append(3)
>>> list2
[5, 3]
>>> list2.sort()
>>> list
<class 'list'>
>>> list2
[3, 5]
>>> #第三点为多态
>>> #第三点为多态
>>> class A:
    def fun(self):
        print("我是小A")
>>> class B:
    def fun(self):
        print('我是小B')

        
>>> a = A()
>>> b = B()
>>> a.fun()
我是小A
>>> b.fun()
我是小B

037类和对象:面向对象的编程

        self是什么?相当于C++中this指针,

>>> class Ball:
	def setName(self, name):
		self.name = name
	def kick(self):
		print('我叫%s,别提我。。' % self.name)

		
>>> a = Ball()
>>> a.setName('球A')
>>> b = Ball()
>>> b.setName('球B')
>>> c = Ball()
>>> c.setName('土豆')
>>> a.kick()
我叫球A,别提我。。
>>> c.kick()
我叫土豆,别提我。。

魔方方法:__init__(self)

>>> class Ball:
	def __init__(self, name):
		self.name = name
	def kick(self):
		print('我叫%s,别提我' % self.name)

	
>>> b = Ball('土豆')
>>> b.kick()
我叫土豆,别提我
公有和私有?

        在python中定义私有变量只需在变量名或函数名前加上“_”两个下划线,这个函数就私有。_类名__变量名

>>> class Person:
	name = '小甲鱼'

	
>>> p = Person()
>>> p.name
'小甲鱼'
>>> class Person:
    __name = '小甲鱼'

    
>>> p = Person()
>>> p.__name
Traceback (most recent call last):
  File "<pyshell#77>", line 1, in <module>
    p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.name
Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    p.name
AttributeError: 'Person' object has no attribute 'name'
>>> class Person:
    __name = '小甲鱼'
    def getName(self):
        return self.__name

    
>>> p = Person()
>>> p.__name
Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.getName()
'小甲鱼'
















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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值