Tools
首页
画图
音乐
采集
记事
博客
实验室
登录
lypeng
146
文章
11
分类
46
记事
分类
生活-[23]
Linux-[24]
前端-[9]
数据库-[16]
PHP-[31]
git-[7]
其他-[6]
python-[20]
算法-[4]
React-Native-[4]
中草药-[2]
广告位1
广告位2
首页
/ python
返回列表
python(六)类、文件读写、发邮件
阅读:719
发布:2018-04-23
作者:lypeng
# 类 1. 类定义的时候,可以传一个参数,object表示基类,其他则表示继承了该类 2. 类,__init__初始化方法 3. 类中的所有方法第一个参数是self 4. 私有化变量,前面加两个下划线 5. __slots__ 表示只允许外部绑定的属性 6. 类中的特殊方法,__iter__迭代 7. getattr()、setattr()以及hasattr()属性相关 ## example1 ```python class Student(object): __slots__ = ('name', 'gender') # 用tuple定义允许绑定的属性名称 def __init__(self, name, gender): self.name = name self.__gender = gender def set_gender(self,gender): if gender=='male' or gender=='female': self.__gender = gender else: raise ValueError('bad value') def get_gender(self): return self.__gender bart = Student('Bart', 'male') if bart.get_gender() != 'male': print('测试失败!') else: bart.set_gender('female2') if bart.get_gender() != 'female': print('测试失败!') else: print('测试成功!') ``` ## example2 使用生成器函数实现可迭代对象,for循环迭代素数 ```python class PrimeNumbers: def __init__(self,start,end): self.start = start self.end = end def isPrimeNum(self,k): if k<2: return False else: for i in range(2,k-1): if k%i == 0: return False return True def __iter__(self): for k in range(self.start,self.end+1): if self.isPrimeNum(k): yield k for x in PrimeNumbers(1,100): print(x) ``` ```python # 浮点数迭代器 class FloatIter: def __init__(self,start,end,step=0.1): self.start = start self.end = end self.step = step def __iter__(self): t = self.start while t<=self.end: yield t t += self.step def __reversed__(self): t = self.end while t>=self.start: yield t t -= self.step for i in FloatIter(1.0,4.0,0.5):print(i) for i in reversed(FloatIter(1.0,4.0,0.5)):print(i) ``` ## 其他属性 ```python # getattr()、setattr()以及hasattr() >>> class MyObject(object): ... def __init__(self): ... self.x = 9 ... def power(self): ... return self.x * self.x ... >>> obj = MyObject() >>> hasattr(obj, 'x') # 有属性'x'吗? True >>> obj.x 9 >>> hasattr(obj, 'y') # 有属性'y'吗? False >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> hasattr(obj, 'y') # 有属性'y'吗? True >>> getattr(obj, 'y') # 获取属性'y' 19 >>> obj.y # 获取属性'y' 19 >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 404 ``` ----------- # 文件读写 ```python #!/usr/bin/python3 # -*- coding: utf-8 -*- # 文件操作 # filepath = '/home/wwwroot/test/python/w.txt' # f = open(filepath,'r',encoding='utf-8',errors='ignore') # f.read() # f.clode() # try: # f = open(filepath, 'r') # print(f.read()) # finally: # if f: # f.close() # with open(filepath, 'r') as f: # print(f.read()) # 调用read(size)方法,每次最多读取size个字节的内容。 # 调用readline()可以每次读取一行内容, # 调用readlines()一次读取所有内容并按行返回list。 # with open(filepath, 'r') as f: # print(f.readline()) #读取一行 # 'a'是追加,w+不起作用 # 'r' open for reading (default) # 'w' open for writing, truncating the file first # 'x' open for exclusive creation, failing if the file already exists # 'a' open for writing, appending to the end of the file if it exists # 'b' binary mode # 't' text mode (default) # '+' open a disk file for updating (reading and writing) # 'U' universal newlines mode (deprecated) # with open('/home/wwwroot/test/python/w.txt','a') as f: # f.write('write file learning222...') # f.close() # with open(filepath, 'r') as f: # for line in f.readlines(): # print(line.strip()) # StringIO # >>> from io import StringIO # >>> f = StringIO() # >>> f.write('hello') # 5 # >>> f.write(' ') # 1 # >>> f.write('world!') # 6 # >>> print(f.getvalue()) # hello world! # 目录操作 # >>> os.mkdir('/home/wwwroot/test/ttt') # >>> os.path.abspath('.') # '/home/lypeng' # os.rmdir('/home/wwwroot/test/ttt') # >>> os.path.split('/home/wwwroot/test/python/k.txt') # ('/home/wwwroot/test/python', 'k.txt') # >>> os.path.splitext('/home/wwwroot/test/python/k.txt') # ('/home/wwwroot/test/python/k', '.txt') # # 对文件重命名: # >>> os.rename('test.txt', 'test.py') # # 删掉文件: # >>> os.remove('test.py') # 显示当前目录下后缀是.py的文件 # [x for x in os.listdir('.') if os.isfile(x) and os.splitext(x)[1]=='.py'] #json与字典转换,json.dumps(dict);json.loads(str) >>> import json >>> d = dict(name='Bob', age=20, score=88) >>> json.dumps(d) '{"age": 20, "score": 88, "name": "Bob"}' >>> json_str = '{"age": 20, "score": 88, "name": "Bob"}' >>> json.loads(json_str) {'age': 20, 'score': 88, 'name': 'Bob'} ``` # 发邮件 安装模块 `pip3 install yagmail` 具体说明参见:https://github.com/kootenpv/yagmail?_blnak ```python #!/usr/bin/python3 # -*- coding: utf-8 -*- import yagmail yag = yagmail.SMTP(user='893371810@qq.com', password='mima', host='smtp.qq.com', port='465') # contents = ['html', '/home/wwwroot/dpshop/a.mp3'] yag.send('893371810@qq.com', "subjects", '
This is the body, and here is just text
') # 发送给谁可以写多个,用list或者tuple,contents可以是个list,可以是字符串,HTML,本地文件绝对地址,如果有本地元素且文件存在,会被当做附件,否则当字符串处理 ```
------本文结束
感谢阅读------
上一篇:
python(五)函数
下一篇:
python3 换国内源