流畅的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)
原文地址:https://www.cnblogs.com/1314520xh/p/12741352.html