流畅的python学习1(小白轻松学python)

网友投稿 330 2022-08-29


流畅的python学习1(小白轻松学python)

#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Created on Mon Apr 20 21:08:08 2020@author: root"""import collectionsCard = collections.namedtuple('Card', ['rank','suit'])class FrenchDeck: ranks = [str(n) for n in range(2,11)]+list('JQKA') suits='spades diamods 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] beer_card = Card('7','diamods')print ('beer_card',beer_card) deck=FrenchDeck()print (len(deck))# example1from random import choicechoice(deck)print (choice(deck))#__getitem__for card in deck: print(card) for card in reversed(deck): print (card) Card('Q','hearts') in deck 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(deck,key=spades_high): print (card) """Python的魔法方法__getitem__ 可以让对象实现迭代功能,这样就可以使用for...in... 来迭代该对象了在用 for..in.. 迭代对象时,如果对象没有实现 __iter__ __next__ 迭代器协议, Python的解释器就会去寻找__getitem__ 来迭代对象 ,如果连__getitem__ 都没有定义,这解释器就会报对象不是迭代器的错误: """ class Animals: def __init__(self,animal_list): self.animals_name=animal_list def __getitem__(self,index): return self.animals_name[index] animals=Animals(['dog','cat','fish']) for animal in animals: print (animals)

#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Created on Mon Apr 20 22:39:15 2020@author: root"""from math import hypotclass Vector: def __init__(self,x=0,y=0): self.x=x self.y=y def __repr__(self): return 'repr 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) a=Vector(1,2) b=Vector(3,4)print (a+b)

心有猛虎,细嗅蔷薇


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python设计模式(Python设计模式(第2版))
下一篇:Springboot整合https的实例代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~