`item`系列学习

2019-09-28  本文已影响0人  陈忠俊

Python 几个常有的内置方法__getitem____setitem____delitem__

有以下代码:

>>> class Test:
...     def __init__(self, **kwargs):
...         for key, value in kwargs.items():
...             setattr(self, key, value)
...     def __setitem__(self, key, value):
...         print("Setting %s to %s" %(key, value))
...         self.__dict__[key] = value
...     def __getitem__(self, key):
...         if hasattr(self, key):
...             print("Getting key: %s" %key)
...             return self.__dict__[key]
...         raise ValueError("No such key")
...     def __delitem__(self, key):
...         if hasattr(self, key):
...             print("Deleting key: %s" %key)
...             del self.__dict__[key]
...         raise ValueError("No such key")
...
>>> teacher = Test(name = 'eclipse', age = 30)
>>> teacher.name
'eclipse'
>>> teacher['name'] = 'alibaba'
Setting name to alibaba
>>> teacher['name']
Getting key: name
'alibaba'
>>> teacher.name
'alibaba'
>>>

当通过key的方式调用实例的属性时,默认调用item方法。下面通过getattrsetattr的实例调用下它们的用法。初始化时调用了setattr,获取属性时,调用了getattr。(这里继承了dict,所以可以通过key的方式引用和赋值。)

>>> class Test2(dict):
...     def __init__(self, name, age):
...         self.name = name
...         self.age  = age
...     def __setattr__(self, key, value):
...         print("setting %s to %s" %(key, value))
...         self[key] = value
...     def __getattr__(self, key):
...         print("Getting key: %s" %key)
...         return self[key]
...
>>> te2 = Test2('hh', 22)
setting name to hh
setting age to 22
>>> te2.name
Getting key: name
'hh'
>>> te2['name']
'hh'

看到别人代码写的好,忍不住抄了过来。学习下。。。

from collections import namedtuple
from random import choice
from random import shuffle
Card = namedtuple('Card', ['rank', 'suit'])
class FranchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')
    suits = ["红桃", "方块", "梅花", "黑桃"]
    def __init__(self):
        self._cards = [Card(rank, suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits]
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, key):
        return self._cards[key]
    def __setitem__(self, key, value):
        self._cards[key] = value
>>> deck = FranchDeck()
>>> deck[0]
Card(rank='2', suit='红心')
>>> choice(deck)
Card(rank='6', suit='梅花')
>>> choice(deck)
Card(rank='A', suit='黑桃')
>>> deck

shuffle方法可以打乱一个可迭代对象的顺序,如列表,元组,字符串等。

>>> line = [1, 2, 3, 4, 5]
>>> shuffle(line)
>>> line
[4, 3, 2, 5, 1]

因此,我们可以用shuffle去洗牌

>>> shuffle(deck)
>>> deck._cards[:3]
[Card(rank='3', suit='红心'), Card(rank='2', suit='黑桃'), Card(rank='K', suit='红心')]
>>> shuffle(deck)
>>> deck._cards[:5]
[Card(rank='9', suit='红心'), Card(rank='8', suit='黑桃'), Card(rank='2', suit='黑桃')]
>>>
上一篇下一篇

猜你喜欢

热点阅读