流畅的python学习1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 20 21:08:08 2020 @author: root """ import collections Card = 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)) # example1 from random import choice choice(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 hypot class 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)
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16