本章概述了python的数据模型,即对python框架的描述,它规范了这门语言自身构建模块的接口,之后通过模拟扑克牌和实现二维向量,简单分析了python中的特殊方法--魔术方法(dunder?method),双下划线方法.如__getitem__,__len__,__add__等
'''
第一章 Python的数据模型
序列 sequence
迭代器 generator
函数 function
类 class
上下文管理器 textmanager
magic method(魔术方法)
__getitem__:
1.执行obj[key]时调用 实现了索引
2.实现了切片
3.实现了迭代和反向迭代
4.隐式实现了__contains__,可以使用in运算符
__len__: 执行len(obj)时调用'''
# 1.1一摞有序的纸牌
# import collections
# from random import choice
# Card = collections.namedtuple('card',['rank','suit'])
#
# class FrenchDeck:
# ranks = [str(x) for x 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]
# if __name__ == '__main__':
# pai = FrenchDeck()
#
# # print(pai[51]) # 索引
# # print(choice(pai))
# # print(pai[:3]) # 切片
# # print(pai[12::13])
#
# # for card in pai: # 迭代
# # print(card)
# # for card in reversed(pai): # 反向迭代
# # print(card)
#
# print(Card(rank='14', suit='spades') in pai)
# print(Card(rank='4', suit='spades') in pai)
#
# # 实现排序
# suit_values = dict(spades = 3,hearts = 2,diamonds = 1,clubs = 0)
# def spades_high(card):
# rank_value = FrenchDeck.ranks.index(card.rank)
# return rank_value * len(suit_values) + suit_values[card.suit]
#
# for card in sorted(pai,key=spades_high):
# print(card)
# 1.2.1 模拟数值类型 实现一个二维向量类(vector)
'''
魔术方法
__repr__: 字符串表示形式
和__str__的区别: 后者是在str()函数被使用,或是用print打印一个对象时使用,
它返回的字符串对终端用户更友好
__abs__:abs(obj)
__add__:obj1 + obj2
__mul__:obj1 * obj2
__truediv__:obj1 / obj2
__mod__: obj1 % obj2
__sub__: obj1 - obj2
__bool__: bool(obj)
bool(x) 默认会调用__bool__,如果没有则调用__len__,结果为0,返回False,否则返回True
'''
from math import hypot
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)
def __abs__(self):
return hypot(self.x,self.y)
def __bool__(self):
return bool(abs(self))
def __add__(self,other):
x = self.x + other.x
y = self.y + other.y
return Vector(x,y)
def __mul__(self, scalar):
return Vector(self.x * scalar,self.y * scalar)
if __name__ == '__main__':
v1 = Vector(3,4)
v2 = Vector(1,2)
print(abs(v1))
print(v1+v2)
print(v1)
|