A Pythonic Card Deck: __len__ & __getitem__ & for 循环的嵌套
1. Example of two-dimensional vector: Vector(2,4) + Vector(2,1) results in Vector(4,5)
import math
# special methods used: __repr__ , __abs__ , __add__ , __mul__
class Vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return "Vector(%r, %r)" % (self.x, self.y)
# we use %r to obtain the standard representation of the attributes to be displayed.
# !r should be used in the str.format method.
def __abs__(self):
return math.hypot(self.x, self.y)
# math.hypot(x, y) 即相当于 math.sqrt(x*x + y*y)
def __bool__(self):
"""
By default, instances of user-defined classes are considered truthy, unless either __bool__ or __len__ is
implemented. Basically, bool(x) calls x.__bool__() and uses the result. If __bool__ is not implemented, Python
tries to invoke x.__len__(), and if that returns zero, bool returns False. Otherwise bool returns True.
:return:
"""
return bool(self.x or self.y)
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y) # create and return a new instance of Vector
def __mul__(self, other):
return Vector(self.x * other, self.y * other)
"""
in both __add__ and __mul__ , the methods should create and return a new instance of Vector, and DO NOT modify
either operand -- 'self' or 'other' (应该生成新的对象)
"""
v1 = Vector(2, 4)
v2 = Vector(2, 1)
print(v2)
print("add: v1 + v2", v1 + v2)
v = Vector(3, 4)
print("abs(3,4)", abs(v))
print("v * 3", v * 3)
print("abs(v*3)", abs(v * 3))
2.1. 列表生成式的嵌套 for 循环:
示例如下:
li1 = range(1,6)
li2 = list("ABC") # list("ABC") 的结果为 ["A", "B", "C"] for m in li1:
for n in li2:
print((m,n)) li = [(m,n) for m in li1 for n in li2]
print(li) # 输出结果:
(1, 'A')
(1, 'B')
(1, 'C')
(2, 'A')
(2, 'B')
(2, 'C')
(3, 'A')
(3, 'B')
(3, 'C')
(4, 'A')
(4, 'B')
(4, 'C')
(5, 'A')
(5, 'B')
(5, 'C')
[(1, 'A'), (1, 'B'), (1, 'C'), (2, 'A'), (2, 'B'), (2, 'C'), (3, 'A'), (3, 'B'), (3, 'C'), (4, 'A'), (4, 'B'), (4, 'C'), (5, 'A'), (5, 'B'), (5, 'C')] # 列表生成式中的 两个 for 循环 作用就相当于 for 循环的嵌套
参考链接: https://www.jb51.net/article/150400.htm
2.2 A Pythonic Card Deck: __len__ & __getitem__
示例如下:
import collections
Card = collections.namedtuple("Card", ["rank", "suit"])
class FrenchDeck(object):
ranks = [str(n) for n in range(2, 11)] + list("JQKA")
suits = "spades diamonds clubs hearts".split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
deck = FrenchDeck()
print(len(deck)) # len() 实际只适合 dict, list 等;想要 适用于 deck ,就需要重写 __len__ 方法
# output:
#
print(deck[0], deck[1]) # __getitem__ delegates to the [] operator
"""
Special methods是理解Python语言的关键之一。例如,__getitem__特殊方法用来支持obj[key]。因此,当实现my_collection[key],解释器实际上调用的是my_collection.__getitem__(key)
"""
# output:
# Card(rank='2', suit='spades') Card(rank='3', suit='spades')
import random
print(random.choice(deck))
print(random.choice(deck))
print(random.choice(deck))
# output:
# Card(rank='8', suit='clubs')
# Card(rank='J', suit='clubs')
# Card(rank='2', suit='diamonds')
"""
random.choice(seq) 的原理:
random.choice内部实现是先用len方法获取总长度然后从0到总长度时间取一个随机数作为索引获取
源码如下:
def choice(self, seq):
# Choose a random element from a non-empty sequence.
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
"""
# 切片: class slice(start, stop[, step])
print(deck[12::13])
# output:
# [Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'),
# Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]
for card in deck:
print(card)
# by implementing the __getitem__ special method, deck is also iterable
# the statement -- for i in x: actually causes the invocation of iter(x), which in turn may call x.__iter__() if that is possible.
# the deck can also be iterated in reverse :
for card in reversed(deck):
print(card)
"""
reversed(seq)
Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).
"""
print(Card("Q", "hearts") in deck)
print(Card("", "beasts") in deck)
# output:
# True
# False
# 特殊方法 __contains__ 是用来进行in检验的。
# Sorting:
"""
要求:
A common system of ranking cards is by rank(with aces being highest),then by suit the order of spades(highest), then hearts,
diamonds, and clubs(lowest).
"""
suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0)
def spades_high(card):
card_rank = FrenchDeck.ranks.index(card.rank)
return card_rank * len(suit_values) + suit_values[card.suit]
for card in sorted(deck, key=spades_high):
# deck 中的每个 item 会传为 spades_high 的参数 传入 spades_high 中
print(card)
"""
By implementing the special methods __len__ and __getitem__ , our FrenchDeck behaves like a standard Python sequence.
The `list.sort` method sorts a list in place -- that is, without making a copy. (list.sort 方法是对一个列表进行【就地】排序;返回 None);
In contrast , the built-in function `sorted` creates a new list and returns it. (返回排序后的 list)
"""
A Pythonic Card Deck: __len__ & __getitem__ & for 循环的嵌套的更多相关文章
- python中的__len__,__getitem__ __setitem__ __delitem__ __contains__
可变集合需要实现: __len__ __getitem__ __setitem__ __delitem__不可变集合需要实现: __len__ __getitem__ __len__:返回 ...
- for循环的嵌套,for循环的穷举迭代
for循环的嵌套 输入一个正整数,求阶乘的和 嵌套 Console.Write("请输入一个正整数:"); int ...
- 【C语言】-循环的嵌套
循环的嵌套:当在一个循环语句中嵌入另一个循环时,成为循环的嵌套. 循环嵌套的形式: (1)for语句中嵌入for语句: for ( ) { for ( ) { ... } } (2)for语句嵌入wh ...
- C语言循环的嵌套
注:参考网络资源拟制,如雷同请见谅循环的嵌套:一个循环体语句中又包含另一个循环语句,称为循环嵌套.嵌套注意事项:1.使用循环嵌套时,内层循环和外层循环的循环控制变量不能相同.2.循环嵌套结构的书写,最 ...
- 2017-2-24 C#基础 for循环的嵌套
用几个练习题演示一下for循环的嵌套 1.打印以下图形 ★★★★★★★★★★★★★★★ namespace _2017_2_24_for循环的嵌套 { class Program { static v ...
- for循环中嵌套setTimeout,执行顺序和结果该如何理解?
这两天在捣鼓作用域的问题,有的时候知识这个东西真的有点像是牵一发而动全身的感觉.在理解作用域的时候,又看到了一道经典的面试题和例子题. 那就是在for循环中嵌套setTimeout延时,想想之前面试的 ...
- for 循环与嵌套
循环:反复执行某段代码.循环四要素:初始条件,循环条件,循环体,状态改变 for(初始条件;循环条件;状态改变){ 循环体} 给出初始条件,先判断是否满足循环条件,如果不满足条件则跳过for语句,如果 ...
- .Net基础篇_学习笔记_第六天_for循环的嵌套_乘法口诀表
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- for循环中嵌套异步请求问题
for循环中嵌套了异步请求会导致顺序错乱,用递归代替for循环,可以保证正常执行顺序:
随机推荐
- 火车购票问题(16年ccf)
火车购票问题(16年ccf) 问题描述 请实现一个铁路购票系统的简单座位分配算法,来处理一节车厢的座位分配. 假设一节车厢有20排.每一排5个座位.为方便起见,我们用1到100来给所有的座位编号,第一 ...
- react 闲谈
从事前端一段时间了,公司用的框架都是vue,但是不知为何对react却情有独钟,这是不是所谓的吃着碗里的看着锅里的 哈哈哈 从头好好总结下react吧 小白一个 大神勿喷 瞎说一 react是由两部分 ...
- flask(3.0)
目录 一.Flask - CBV 二.Flask - Session 1.安装flask-session 2.回顾flask自带的session的使用方法 3.flask-session的使用(以保存 ...
- 3年磨一剑,我的前端数据 mock 库 http-mock-middleware
不好意思,离开博客园4年多了,一回来就是为自己打广告,真是害羞啊... http-mock-middleware 是我最近完成的一个前端数据 mock 库.它是我汇总近3年工作经验而诞生的一个工具,使 ...
- Day03:文本数据IO操作 / 异常处理
文本数据IO操作 Reader和Writer 字符流原理 Reader是字符输入流的父类 Writer是字符输出流的父类. 字符流是以字符(char)为单位读写数据的.一次处理一个unicode. ...
- C# 关于App.config
App.config是winfrom等程序的应用程序配置文件,用来存放一些参数. app.config只会在应用程序启动时加载一次. 当程序在运行中修改app.config中的参数是不会生效,必须要重 ...
- C++学习笔记-继承中的构造与析构
C++存在构造函数与析构函数,继承中也存在构造和析构函数.继承中的构造和析构函数与普通的构造析构有细微差别. 赋值兼容性原则 #include "iostream" using n ...
- BTree B+Tree
简介 B 树是为了磁盘或其它存储设备而设计的一种多叉平衡查找树.(相对于二叉,B树每个内结点有多个分支,即多叉)B树又可以写成B-树/B-Tree,并不是B“减”树,横杠为连接符,容易被误导首先我们介 ...
- 语言I博客作业04
问题 答案 这个作业属于哪个课程 C语言程序设计II 这个作业的要求在哪里 https://edu.cnblogs.com/campus/zswxy/CST2019-3/homework/9771 我 ...
- Centos7 下安装docker
Docker 运行在 CentOS 7 上,要求系统为64位.系统内核版本为 3.10 以上. Docker 运行在 CentOS-6.5 或更高的版本的 CentOS 上,要求系统为64位.系统内核 ...