1 反射

反射的精髓是通过字符串去获取对象属性的值

1.1 基于类和对象反射的属性

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 # 基于类和对象反射的属性
class People:
country = 'China'
def __init__(self,name):
self.name = name
def run(self):
print('%s is running'%self.name) p = People('egon') # 实例化一个People对象p
print('基于类和对象反射的属性')
# hasattr: 判断类或对象是否存在某个属性,存在返回True,否则返回False
print('hasattr------------>')
print(hasattr(p,'name'))
print(hasattr(People,'name'))
# getattr: 获取类或对象的属性
print('getattr------------->')
print(getattr(p,'run'))
print(getattr(People,'run'))
func = getattr(p,'run')
func() # hasattr和getattr结合使用
print('hasattr & getattr------------>')
if hasattr(p,'run'):
func = getattr(p,'run')
func() # setattr: 修改或新增类或对象的属性
print('setattr-------------->')
print(p.__dict__)
setattr(p,'name','cobila') # 用于修改
setattr(p,'age',18) # 用于新增
print(p.__dict__) # delattr: 删除类或对象的属性
print('delattr------------->')
print(p.__dict__)
delattr(p,'name')
print(p.__dict__)

1.2 基于当前模块反射的属性

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 import sys
x = 1111
class Foo:
pass def s1():
print('s1')
def s2():
print('s2') this_module = sys.modules[__name__] # 获取当前模块
print(this_module)
print(hasattr(this_module,'s1'))
print(getattr(this_module,'s1')) # print(this_module.s1)
print(hasattr(this_module,'s2'))
print(getattr(this_module,'s2')) # print(this_module.s2)

1.3 反射的应用1

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 import sys def add():
print('add')
def delete():
print('delete')
def update():
print('update')
def get():
print('get') this_module = sys.modules[__name__]
func_dict = {'add':add,'delete':delete,'update':update,'get':get}
while True:
choice = input('>>').strip()
if hasattr(this_module,choice):
func_dict[choice]

1.3 反射的应用2

FTP Client

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 class FtpClient:
'ftp客户端,但是还么有实现具体的功能'
def __init__(self,addr):
print('正在连接服务器[%s]'%addr)
self.addr = addr
# def get(self):
# print('get')

FTP Server

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 import ftp_client
f1 = ftp_client.FtpClient('192.168.1.1')
if hasattr(f1,'get'):
func_get = getattr(f1,'get')
func_get()
else:
print('Method get not found') print('处理其他逻辑') # 不影响其他功能实现

2 类内置attr

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 # class __getattr__ __setattr__ __delattr__
class Foo:
def __init__(self,name,age):
self.name = name # 会触发__setattr__
self.age = age # 会触发__setattr__ def __setattr__(self, key, value):
print('setattr')
if not isinstance(value,str): # 可以设置类型限制
raise TypeError("must be str")
self.__dict__[key] = value def __getattr__(self, item): # 属性不存在时会执行此函数
print('getattr') def __delattr__(self, item):
print('delattr')
self.__dict__.pop(item) f = Foo('egon',18) # 初始化会触发__setattr__
f.name = 'cobila' # 会触发__setattr__
print(f.__dict__)
f.xxx # 找不到xxx属性时会触发__getattr__
del f.age # 会触发__delattr__
print(f.__dict__)

3 定制自己的数据类型

3.1 继承的方式

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 # 定制自己的数据类型 通过继承
class List(list):
def append(self, p_object):
if not isinstance(p_object,int):
raise TypeError('Must be int')
super().append(p_object) def insert(self,index,p_object):
if not isinstance(p_object, int):
raise TypeError('Must be int')
super().insert(index,p_object) l1 = List([1,2,3])
print(l1)
l1.append(4)
print(l1)
# l1.append('test') # 会抛出TypeError异常
l1.insert(0,5)
# l1.insert(0,'5') # 会抛出TypeError异常
print(l1)

3.2 授权的方式

#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/4/24 # 定制自己的open函数 不通过继承 通过授权的方式实现定制自己的数据类型
import time
print(time.strftime('%Y-%m-%d %X')) # 打印当前时间
class Open:
def __init__(self,filepath,mode='r',encoding='utf-8'):
self.filepath = filepath
self.mode = mode
self.encoding = encoding
self.f = open(filepath,mode,encoding=encoding)
def write(self,line):
t = time.strftime('%Y-%m-%d %X')
self.f.write('%s %s\n'%(line,t))
def __getattr__(self,item):
func = getattr(self.f,item)
return func f = Open('b.txt','w')
f.write('test write')
f.write('test write')
f.write('test write')
f.close() f = Open('b.txt','r+')
res = f.read()
print(res)
f.close()

Python全栈之路-Day31的更多相关文章

  1. Python全栈之路目录结构

    基础 1.Python全栈之路-----基础篇 2.Python全栈之路---运算符与基本的数据结构 3.Python全栈之路3--set集合--三元运算--深浅拷贝--初识函数 4.Python全栈 ...

  2. Python全栈之路----目录

    Module1 Python基本语法 Python全栈之路----编程基本情况介绍 Python全栈之路----常用数据类型--集合 Module2 数据类型.字符编码.文件操作 Python全栈之路 ...

  3. Python全栈之路----常用模块----hashlib加密模块

    加密算法介绍 HASH       Python全栈之路----hash函数 Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列 ...

  4. python 全栈之路

    目录 Python 全栈之路 一. Python 1. Python基础知识部分 2. Python -函数 3. Python - 模块 4. Python - 面对对象 5. Python - 文 ...

  5. Python全栈之路----函数----返回值

    函数外部的代码想要获取函数的执行结果,就可以在函数里用return语句,把结果返回. def stu_register(name,age,course='PY',country='CN'): prin ...

  6. Python全栈之路----常用模块----软件开发目录规范

    目录基本内容 log  #日志目录 conf  #配置目录 core/luffycity  #程序核心代码目录  #luffycity 是项目名,建议用小写 libs/modules  #内置模块 d ...

  7. Python全栈之路----常用模块----shutil模块

    高级的 文件.文件包.压缩包 处理模块   参考Python之路[第四篇]:模块     #src是原文件名,fdst是新文件名 shutil.copyfileobj(fsrc, fdst[, len ...

  8. Python全栈之路----Python2与Python3

    金角大王Alex  python 之路,致那些年,我们依然没搞明白的编码 python2与python3的区别 py2 str = bytes 为什么有bytes? 是因为要表示图片.视频等二进制格式 ...

  9. Python全栈之路----函数进阶----装饰器

    Python之路,Day4 - Python基础4 (new版) 装饰器 user_status = False #用户登录后改为True def login(func): #传入想调用的函数名 de ...

随机推荐

  1. Tyvj P1813 [JSOI2008]海战训练

    P1813 [JSOI2008]海战训练 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 为了准备高层峰会,元首命令武装部队必须处于高度戒备.警察将监视每一条 ...

  2. 长连接 Socket.IO

    概念 说到长连接,对应的就是短连接了.下面先说明一下长连接和短连接的区别: 短连接与长连接 通俗来讲,浏览器和服务器每进行一次通信,就建立一次连接,任务结束就中断连接,即短连接.相反地,假如通信结束( ...

  3. oracle xe 数据库用户操作

    在system账号登录获得system权限,然后对用户进行操作 --创建表空间create tablespace tablespace_name datafile 'D:\tablespace_nam ...

  4. iOS网络编程笔记——XML文档解析

    今天利用多余时间研究了一下XML文档解析,虽然现在移动端使用的数据格式基本为JSON格式,但是XML格式毕竟多年来一直在各种计算机语言之间使用,是一种老牌的经典的灵活的数据交换格式.所以我认为还是很有 ...

  5. React-Native 开发(二) 在react-native 中 运用 redux

    前提: 一个小web前端,完全不会android 跟iOS 的开发,首次接触,有很多不懂的问题.请见谅. 环境: win7 上一篇 : React-Native 开发(一) Android环境部署,H ...

  6. java程序包不存在

    当把classpath和path设置好之后. 自己写了个类的,然后放在test_package\mypackage路径下.主函数要用到.但是却出错了. 我一开始怀疑自己的classpath配置错了,在 ...

  7. Tcl与Design Compiler (六)——基本的时序路径约束

    本文属于原创手打(有参考文献),如果有错,欢迎留言更正:此外,转载请标明出处 http://www.cnblogs.com/IClearner/  ,作者:IC_learner 时序约束可以很复杂,这 ...

  8. 常用linux命令及其设置

    完成一个运维的工作,以下的命令和配置是经常会用到的,总结一下工作以来的命令和配置 linux常用命令 linux客户端挂接(mount)其他linux系统或UNIX系统的NFS共享 $ mkdir – ...

  9. ajax大洋第一步

    Ajax工具包 Ajax并不是一项新技术,它实际上是几种技术,每种技术各尽其职,以一种全新的方式聚合在一起. 服务器端语言:服务器需要具备向浏览器发送特定信息的能力.Ajax与服务器端语言无关. XM ...

  10. JDBC基础学习(二)—PreparedStatement

    一.PreparedStatement介绍     在SQL中包含特殊字符或SQL的关键字(如: ' or 1 or ')时Statement将出现不可预料的结果(出现异常或查询的结果不正确),可用P ...