像计算机科学家一样学习python(11)

继承+python拾珍

Python学习笔记-像计算机科学家一样学习python(11)

继承

Python中有哪些魔法函数?

Python中每个魔法函数都对应了一个Python内置函数或操作,比如__str__对应str函数,__lt__对应小于号<等。Python中的魔法函数可以大概分为以下几类:

类的构造、删除:

Python
object.__new__(self, ...)
object.__init__(self, ...)
object.__del__(self)

二元操作符:

Python
+	object.__add__(self, other)
-	object.__sub__(self, other)
*	object.__mul__(self, other)
//	object.__floordiv__(self, other)
/	object.__div__(self, other)
%	object.__mod__(self, other)
**	object.__pow__(self, other[, modulo])
<<	object.__lshift__(self, other)
>>	object.__rshift__(self, other)
&	object.__and__(self, other)
^	object.__xor__(self, other)
|	object.__or__(self, other)

扩展二元操作符:

Python
+=	object.__iadd__(self, other)
-=	object.__isub__(self, other)
*=	object.__imul__(self, other)
/=	object.__idiv__(self, other)
//=	object.__ifloordiv__(self, other)
%=	object.__imod__(self, other)
**=	object.__ipow__(self, other[, modulo])
<<=	object.__ilshift__(self, other)
>>=	object.__irshift__(self, other)
&=	object.__iand__(self, other)
^=	object.__ixor__(self, other)
|=	object.__ior__(self, other)

一元操作符:

Python
-	object.__neg__(self)
+	object.__pos__(self)
abs()	object.__abs__(self)
~	object.__invert__(self)
complex()	object.__complex__(self)
int()	object.__int__(self)
long()	object.__long__(self)
float()	object.__float__(self)
oct()	object.__oct__(self)
hex()	object.__hex__(self)
round()	object.__round__(self, n)
floor()	object__floor__(self)
ceil()	object.__ceil__(self)
trunc()	object.__trunc__(self)

比较函数:

Python
<	object.__lt__(self, other)
<=	object.__le__(self, other)
==	object.__eq__(self, other)
!=	object.__ne__(self, other)
>=	object.__ge__(self, other)
>	object.__gt__(self, other)

类的表示、输出:

Python
str()	object.__str__(self) 
repr()	object.__repr__(self)
len()	object.__len__(self)
hash()	object.__hash__(self) 
bool()	object.__nonzero__(self) 
dir()	object.__dir__(self)
sys.getsizeof()	object.__sizeof__(self)

类容器:

Python
len()	object.__len__(self)
self[key]	object.__getitem__(self, key)
self[key] = value	object.__setitem__(self, key, value)
del[key] object.__delitem__(self, key)
iter()	object.__iter__(self)
reversed()	object.__reversed__(self)
in操作	object.__contains__(self, item)
字典key不存在时	object.__missing__(self, key)

练习

18-2(未完成)

Python
class Card:
    """卡片对象
    """
    suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
    rank_names = [None, "Ace", "2", "3", "4", "5", "6", "7", 
                "8", "9", "10", "Jack", "Queen", "King"]
    def __init__(self, suit = 0, rank = 2):
        """卡牌对象初始化
        """
        self.rank = rank    
        self.suit = suit
    
    
    def __str__(self):
        return '%s of %s' %(Card.rank_names[self.rank], Card.suit_names[self.suit])

    def __lt__(self, other):
        # 检查花色
        t1 = self.suit, self.rank
        t2 = other.suit, other.rank
        return t1 < t2

class Deck:
    """卡组对象
    """

    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(suit, rank)
                self.cards.append(card)

    def __str__(self):
        res = []
        for card in self.cards:
            res.append(str(card))
        return '\n'.join(res)

    def pop_card(self):
        return self.card.pop()
    
    def add_card(self, card):
        self.cards.append(card)
    
    def shuffer(self):
        random.shuffer(self.cards)

    def sort(self):
        self.cards.sort()
    


class Hand(Deck):
    """手牌对象
    """

    def __init__(self, lable = ''):
        self.cards = []
        self.label = lable


deck = Deck()
card = deck.pop_card()
hand.add_card(card)
print(hand)

Python拾珍

19.1 条件表达式

Python
if x > 0:
    y = math.log(x)
else:
    y = float('nan')
    
更改为:

y = math.log(x) if x > 0 else float('man')

需要注意的是,如果写成 y = math.log(x) if x > 0 else float('man') 的话, 就会报错:SyntaxError: can't assign to conditional expression

19.2 列表理解

Python
res = []
for s in t:
    res.append(s.capitalize())
return res

更改为:
    
return [s.capitalize() for s in t]

19.3 生成器表达式

sum(x**2 for x in range(5))

19.4 anyall

Python
def avoids(word, forbidden):
    return not any(letter in forbidden for letter in word)
练习:
def uses_all(word, required):
    return all(letter in word for letter in required)

19.5 集合

set(a) <= set(b)用来检查 a 是否是 b 的子集。

19.6 命名元组

Python
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

19.9 收集关键词参数

关键词实参:带名字的实参

练习

Python
def binomial_coeff(n, k):
    """计算(n,k)的二项式系数
    n:试验次数
    k: 成功次数

    返回: int
    """
    memo = {(0, 1): 0, (1, 0): 1}
    if (n, k) in memo:
        return memo[k, n]
    if k == 0:
        memo[k, n] = 1
        return 1
    if n == 0:
        memo[k, n] = 0
        return 0

    res = binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1)
    memo[k, n] = res
    return res

print(binomial_coeff(8, 9))
最后编辑于
文章链接: http://pheustal.com/2020/01-04/thinkpython
本作品采用CC-BY-SA许可。