- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Python进阶之自定义对象实现切片功能由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
切片是 Python 中最迷人最强大最 Amazing 的语言特性(几乎没有之一),在《Python进阶:切片的误区与高级用法》中,我介绍了切片的基础用法、高级用法以及一些使用误区。这些内容都是基于原生的序列类型(如字符串、列表、元组......),那么,我们是否可以定义自己的序列类型并让它支持切片语法呢?更进一步,我们是否可以自定义其它对象(如字典)并让它支持切片呢?
1、魔术方法:__getitem__() 。
想要使自定义对象支持切片语法并不难,只需要在定义类的时候给它实现魔术方法 __getitem__() 即可。所以,这里就先介绍一下这个方法.
语法: object.__getitem__(self, key) 。
官方文档释义:Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised. 。
概括翻译一下:__getitem__() 方法用于返回参数 key 所对应的值,这个 key 可以是整型数值和切片对象,并且支持负数索引;如果 key 不是以上两种类型,就会抛 TypeError;如果索引越界,会抛 IndexError ;如果定义的是映射类型,当 key 参数不是其对象的键值时,则会抛 KeyError .
2、自定义序列实现切片功能 。
接下来,我们定义一个简单的 MyList ,并给它加上切片功能。(PS:仅作演示,不保证其它功能的完备性).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class
MyList():
def
__init__(
self
):
self
.data
=
[]
def
append(
self
, item):
self
.data.append(item)
def
__getitem__(
self
, key):
print
(
"key is : "
+
str
(key))
return
self
.data[key]
l
=
MyList()
l.append(
"My"
)
l.append(
"name"
)
l.append(
"is"
)
l.append(
"Python猫"
)
print
(l[
3
])
print
(l[:
2
])
print
(l[
'hi'
])
|
### 输出结果: key is : 3 Python猫 key is : slice(None, 2, None) ['My', 'name'] key is : hi Traceback (most recent call last): ... TypeError: list indices must be integers or slices, not str 。
从输出结果来看,自定义的 MyList 既支持按索引查找,也支持切片操作,这正是我们的目的.
特别需要说明的是,此例中的 __getitem__() 方法会根据不同的参数类型而实现不同的功能(取索引位值或切片值),也会妥当地处理异常,所以并不需要我们再去写繁琐的处理逻辑。网上有不少学习资料完全是在误人子弟,它们会教你区分参数的不同类型,然后写一大段代码来实现索引查找和切片语法,简直是画蛇添足。下面的就是一个代表性的错误示例:
1
2
3
4
5
6
7
8
9
10
|
###略去其它代码####
def
__getitem__(
self
, index):
cls
=
type
(
self
)
if
isinstance
(index,
slice
):
# 如果index是个切片类型,则构造新实例
return
cls
(
self
._components[index])
elif
isinstance
(index, numbers.Integral):
# 如果index是个数,则直接返回
return
self
._components[index]
else
:
msg
=
"{cls.__name__} indices must be integers"
raise
TypeError(msg.
format
(
cls
=
cls
))
|
3、自定义字典实现切片功能 。
切片是序列类型的特性,所以在上例中,我们不需要写切片的具体实现逻辑。但是,对于其它非序列类型的自定义对象,就得自己实现切片逻辑。以自定义字典为例(PS:仅作演示,不保证其它功能的完备性):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class
MyDict():
def
__init__(
self
):
self
.data
=
{}
def
__len__(
self
):
return
len
(
self
.data)
def
append(
self
, item):
self
.data[
len
(
self
)]
=
item
def
__getitem__(
self
, key):
if
isinstance
(key,
int
):
return
self
.data[key]
if
isinstance
(key,
slice
):
slicedkeys
=
list
(
self
.data.keys())[key]
return
{k:
self
.data[k]
for
k
in
slicedkeys}
else
:
raise
TypeError
d
=
MyDict()
d.append(
"My"
)
d.append(
"name"
)
d.append(
"is"
)
d.append(
"Python猫"
)
print
(d[
2
])
print
(d[:
2
])
print
(d[
-
4
:
-
2
])
print
(d[
'hi'
])
|
### 输出结果: is {0: 'My', 1: 'name'} {0: 'My', 1: 'name'} Traceback (most recent call last): ... TypeError 。
上例的关键点在于将字典的键值取出,并对键值的列表做切片处理,其妙处在于,不用担心索引越界和负数索引,将字典切片转换成了字典键值的切片,最终实现目的.
4、小结 。
最后小结一下:本文介绍了__getitem__() 魔术方法,并用于实现自定义对象(以列表类型和字典类型为例)的切片功能,希望对你有所帮助。也希望大家多多支持我.
原文链接:https://my.oschina.net/u/4051725/blog/2993830 。
最后此篇关于Python进阶之自定义对象实现切片功能的文章就讲到这里了,如果你想了解更多关于Python进阶之自定义对象实现切片功能的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
MySQL表的增删改查(进阶) 1. 数据库约束 约束类型 说明 示例 NULL约束 使用NOT NULL指定列不为空 name varchar(20) not null, UNIQUE唯一约束 指定
多线程(进阶) 1. 常见的锁策略 1.1 乐观锁 悲观锁 乐观锁 : 总是假设最好的情况,每次去拿数据的时候都认为别人不会修改数据,但是在对数据提交更新的时候,再去判断这个数据在这个期间是否有别人对
我相信在正确编码的系统中-错误(作为错误或异常)应该是不可能的(DB/memcached服务器故障导致查询失败)。我们的代码不应依赖任何假设才能正常工作,并且应尽可能地证明其正确性。 但是,为了确保我
1. 前言 泛型代码让你能根据你所定义的要求写出可以用于任何类型的灵活的、可复用的函数。你可以编写出可复用、意图表达清晰、抽象的代码。 泛型是 Swift 最强大
一、创建质量配置及关联项目 1.新建一个java代码质量配置 2.为配置添加规则 确认有4条规则了 为项目更换扫描配置 二、创建质量阈关联项目 1.
完整jenkinsfile 、sharelibrary 及jenkins配置见最后 一、gitlab push分支自动匹配 1.添加Generic Webhook插件参数,获取本次提交的分支信息
1.gitlab创建新应用 2.jenkins安装gitlab插件 3.插件安装完成后全局安全配置中使用并配置gitlab认证 4.注销重新登录后自动使用gitlab当前登录
一、部署jenkins master 1.创建Deployment YAML文件 apiVersion: apps/v1 kind: Deployment metadata: name: je
一、docker安装nexus wget https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo yum clean all
一、新建library文件 build.groovy package org.devops // 构建类型 def Build(buildType,buildShell){
一、制品获取 1.安装及配置插件 配置插件(jenkins项目中) 2.选择对应的制品 3.修改jenkins file // 新增以下代码 String artifactU
1.github创建OAuth 2.jenkins安装并配置github认证插件 jenkins配置使用github认证 3.注销重新登录
一、添加测试Maven项目 1.新建一个gitlab项目 2.导入simple-java-maven-app仓库代码(可以去github或者Gittree上都有) 3.配置mvn 国内源
一、添加AnsiColor插件 二、查看插件语法 1.打开任意pipline项目配置,找到流水线语法,并点击 跳转连接,选择插件,查看帮助 三、修改sharelibrary脚本,优
一、Pipeline概念 1 node/agent(节点) 节点是一个机器,可以是Jenkins的master节点也可以是slave节点。通过node指定当前job运行的机器(这个是脚本式语法)。
一、插件备份和恢复 1.安装备份插件 重启系统后查看 2.配置周期备份 点击进入,点击Settings Backup only builds marked to keep
一、.部署LDAP 这里使用容器部署,手动部署参考:https://www.cnblogs.com/panwenbin-logs/p/16101045.html 1.安装docker wget -
由于sonarqube开源版本不支持多分支管理,在扫描所有分支的时候都会指定同一个sonar项目,不便于我们查看 一、下载开源插件 项目地址:https://github.com/mc1arke/
一、手动测试 注意此版本已经内置包含Java语言扫描插件,不再需要单独安装 1.clone代码 git clone git@192.168.1.128:root/demo-maven-serv
我有下一种情况。 从 PHP 表单中我只获得公司 ID 我需要使用该公司 ID 排列所有用户名 我需要数组并将具有该用户名的所有日志导出到表 我的问题是,当我尝试下一步时: $sql2 = "SELE
我是一名优秀的程序员,十分优秀!