python 特殊方法实例
import collections from random import choice card = collections.namedtuple('Card',['rank','suit']) #构建一个命名元组 class FrenchDeck: ranks = [str(n) for n in range(2,11)] + list('JQKA') # 创建所有纸牌数A-K suit = '黑桃 方块 梅花 红心'.split() # 创建不同的纸牌花色 def __init__(self): self._cards = [Card(ranks,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)) # 获取整套牌的数量 52 print(deck[0]) # 获取第一张牌 Card(rank='2',suit='黑桃') choice(deck) # 随机选取其中某张牌 Card(rank='3',suit='梅花') Card(rank='5',suit='红心') #排序 suit_values = dict(黑桃 = 3,方块 = 2,梅花 = 1,红心 = 0) # 定义一个字典保存不同花色对应的权重值 def spades_high(card): # 定义升序函数 rank_value = FrenchDeck.ranks.index(card.rank) # 找到数字的索引值 return rank_value * len(suit_values) + suit_values[card.suit] # 返回索引值*4 +对应的权重值 # 对所有卡牌进行排序 for card in sorted(deck,key = spades_high): print(card)
模拟数值类型
from math import hypot class Vector(object): """docstring for 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)