一摞python风格的纸牌
import collections
from random import choice
card = collections.namedtuple("card", ["rank", "suit"]) # namedtuple()构建少数只有属性没有方法的对象
class FrenchDeck:
ranks = [str(n) for n in range(2, 10+1)] + list("AJQK")
suits = "spades diamonds clubs hearts".split()
def __init__(self):
self._cards = [card(rank, suit) for rank in self.ranks for suit in self.suits]
def __len__(self): # thon中的特殊方法
return len(self._cards)
def __getitem__(self, item): # 特殊方法
return self._cards[item]
deck = FrenchDeck()
print(len(deck))
print(deck[10])
print(choice(deck))
实现了__getitem__方法,这一摞纸牌就比那成可迭代的,迭代通常是隐式的,如果没有实现__contain__方法,那么in运算符就会按顺序做一次迭代搜索!
定义Vecor类:
实现python中的特殊方法。重载有些运算符
from math import hypot
class Vector: # 默认继承object
"""
实现六个特殊方法
"""
def __init__(self, x=0, y=0): # 初始化方法
self.x = x
self.y = y
def __repr__(self):
"""
实现repr方法,__repr__是python的内置函数,它能把一个对象
以字符串的形式表现出来以便辨认
:return:
"""
# return "Vector(%r, %r)" % (self.x, self.y) # 两种方法都可以
return "Vector({}, {})".format(self.x, self.y)
def __abs__(self): # 相当于重载abs()方法 c++中operator
"""
hyplot函数, 返回sqrt(x*x+y*y)
:return:
"""
return hypot(self.x, self.y)
def __bool__(self): # 相当于重载数值类型里面的bool
"""
如果是非零向量,返回true
:return:
"""
return bool(self.x or self.y)
def __add__(self, other):
"""
重载+运算符, other相当于一个Vector对象
:param other:
:return:
"""
return Vector(self.x + other.x, self.y + other.y)
def __mul__(self, other):
"""
重载*
:param other: 标量
:return:
"""
return Vector(self.x * other, self.y * other)
if __name__ == "__main__":
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)
print(abs(v2))
print(v1 * 3)