一:__init__、__len__、__getitem__
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
print(self._cards)
def __len__(self):
print("len")
return len(self._cards)
def __getitem__(self, position):
print("getitem")
return self._cards[position]
print(Card('7', 'diamonds'))
deck = FrenchDeck() # 执行__init__方法
print(len(deck)) # 执行__len__方法
print(deck[0]) # 执行__grtitem__ 方法
print(deck[:3]) # 执行__grtitem__ 方法
# 可迭代
for card in deck: # 执行__grtitem__ 方法
print(card)
二:__repr__、__abs__、__bool__、__add__、__mul__
from math import hypot
class Vector:
def __init__(self,x=0,y=0):
print("__init__")
self.x = x
self.y = y
def __repr__(self):
print("__repr__")
return 'Vector(%r,%r)' %(self.x, self.y)
def __abs__(self):
print("__abs__")
return hypot(self.x,self.y)
# def __bool__(self):
# print("__bool__")
# return bool(abs(self))
#另外一种实现方法
def __bool__(self):
print("__bool__")
return bool(self.x or self.y)
def __add__(self, other):
print("__add__")
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __mul__(self, scalar):
print("__mul__")
return Vector(self.x * scalar, self.y * scalar)
v1 = Vector(2,3)
v2 = Vector(1,5)
print(abs(v1))
print(v1+v2)
print(v1*2)
print(bool(v1))
output:
__init__
__init__
__abs__
3.605551275463989
__add__
__init__
__repr__
Vector(3,8)
__mul__
__init__
__repr__
Vector(4,6)
__bool__
True
&spm=1001.2101.3001.5002&articleId=108747427&d=1&t=3&u=fbbab86900814bf1b389d0623df7e6b4)
1255

被折叠的 条评论
为什么被折叠?



