item系列内置方法重构类

item系列 和对象使用[]访问值有联系
obj = {'k':'v'}
print(obj)   # 字典的对象
print(obj['k'])

在有些内置的模块中,有一些特殊的方法,要求对象必须实现__getitem__/__setitem__才能使用

1.类似字典的key:value

class A:
    def __getitem__(self, item):
        return getattr(self,item)
    def __setitem__(self, key, value):
        setattr(self,key,value*2)
    def __delitem__(self, key):
        delattr(self,key)
a = A()
# a.k2 = 'v2'
# print(b.k2)
a['k1'] = 'v1'  # __setitem__
print(a['k1'])  # __getitem__
del a['k1']     # __delitem__
print(a['k1'])

2.类似列表的索引

class B:
    def __init__(self,lst):
        self.lst = lst
    def __getitem__(self, item):
        return self.lst[item]
    def __setitem__(self, key, value):
        self.lst[key] = value
    def __delitem__(self, key):
        self.lst.pop(key)
b = B(['111','222','ccc','ddd'])
print(b.lst[0])
print(b[0])
b[3] = 'alex'
print(b.lst)
del b[2]
print(b.lst)
纸牌游戏1 用对象名直接获取对象全部内容
class FranchDeck: 
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = ['红心','方块','梅花','黑桃']

    def __init__(self):
        self._cards = [(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]
    def __repr__(self): #使得打印对象名时 返回的是对象
        print(66)
        return repr(list(self))  #因为实现了item系列方法,所以使对象变成了可迭代对象
    def __len__(self):
        print(44)
        return len(self._cards)

    def __getitem__(self, item):
        print(33)
        return self._cards[item]

    def __setitem__(self, key, value):
        print(55)
        self._cards[key] = value

#
deck = FranchDeck()
print(deck)
from random import choice  #随机选择一个 需要实现 len方法
print(choice(deck))
print(choice(deck))

from random import shuffle #重新排序  需要实现 len 方法 
shuffle(deck)  
print(deck[:6])
纸牌游戏2 不用对象名 而是用对象的属性
class FranchDeck: #纸牌游戏2 不用对象名 而是用对象的属性
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = ['红心','方板','梅花','黑桃']

    def __init__(self):
        self.cards = [(rank,suit) for rank in FranchDeck.ranks
                                        for suit in FranchDeck.suits]

    # def __len__(self):
    #     return len(self._cards)
    #
    # def __getitem__(self, item):
    #     return self._cards[item]
    #
    # def __setitem__(self, key, value):
    #     self._cards[key] = value

deck = FranchDeck()
deck_lis=deck.cards
print(deck_lis)     #因为对象的这个属性本身就是一个列表对象,而列表对象内部是实现了      item系列方法的
from random import choice #随机选择
print(choice(deck_lis))
print(choice(deck_lis))
#
from random import shuffle #打乱顺序 重新洗牌
shuffle(deck_lis)
print(deck_lis[:6])

  

posted @ 2018-08-03 16:31  最后一个老实人  阅读(184)  评论(0编辑  收藏  举报
W3School 在线教程