2014-10-05 31 views
0

我在看別人的代碼,試圖向他們學習,我對他們所做的一些事情有疑問。或分配

這是從鏈路

self.sentence = sentence or "" 

是什麼或賦值操作符做行16?

我試着自己運行這個,如果句子被定義,那麼它被分配給self.sentence,否則如果它沒有被分配,我會得到一個NameError異常。

https://github.com/xavier/exercism-assignments/blob/master/python/bob/bob.py

+0

如果'sentence'評估爲'false',它會將'''''賦值給'self.sentence'。否則(如果'句子'是推定的有效句子),那麼它將'self.sentence'賦予'句子'。 – 2014-10-05 04:47:20

+0

@ಠ_ಠ:這似乎更像是一個答案,而不是評論。 – DSM 2014-10-05 04:49:05

+0

https://docs.python.org/2/library/stdtypes.html的5.2節解釋了「a或b」的含義。 – 2014-10-05 04:50:46

回答

3

or是懶操作者,並返回第一個值,這是 'trueish'(bool(value) is True)。這個習語被用來分配一個值,或者如果它是空的,則是別的。

在這種情況下,它可能會防止分配None,其值爲False,但作者想確定,總是會分配一個string - 在這種情況下爲空字符串。

2

在示例代碼,這會更有意義,如果__init__()有一個默認的說法:

class Fake: 
    def __init__(self, sentence=None): 
     self.sentence = sentence or '<empty>' 

    def print_me(self): 
     print(self.sentence) 

a = Fake('A real sentence') 
b = Fake() 

a.print_me() 
b.print_me() 

輸出:

[email protected]:~/src/sandbox$ ./def.py 
A real sentence 
<empty> 
[email protected]:~/src/sandbox$ 

在這種特殊情況下,def __init__(self, sentence='<empty>'):其次self.sentence = sentence會同樣做不過,在處理可變對象(如列表)時,這可能會更有用,因爲def __init__(self, sentence=[]):只會評估一次,所有類都會參考相同的默認列表。改爲指定None作爲默認值,並在__init__()中創建單獨的空列表可以避免此行爲。

例如:

#!/usr/bin/env python 

class Weird: 
    def __init__(self, the_list=[]): # <--- Don't do this 
     self.the_list = the_list 

    def append(self, value): 
     self.the_list.append(value) 

    def print_me(self): 
     print(self.the_list) 

class Normal: 
    def __init__(self, the_list=None): 
     self.the_list = the_list or [] 

    def append(self, value): 
     self.the_list.append(value) 

    def print_me(self): 
     print(self.the_list) 

print("Weird output:") 
a = Weird() 
b = Weird() 
a.append(1) 
a.append(2) 
a.print_me() 
b.print_me() 

print("Normal output:") 
c = Normal() 
d = Normal() 
c.append(1) 
c.append(2) 
c.print_me() 
d.print_me() 

輸出:

[email protected]:~/src/sandbox$ ./def2.py 
Weird output: 
[1, 2] 
[1, 2] 
Normal output: 
[1, 2] 
[] 
[email protected]:~/src/sandbox$ 

在第一種情況下,你可能期望每個對象以獲得自己的空單,但你可以看到,當您添加的東西a ,他們也被追加到b,因爲ab共享相同的列表。這不會發生在第二種情況下,因爲我們將默認值指定爲None而不是[],然後在您的問題中使用該習語。當the_listNone時,the_list or []將評估爲[]。如果不是,它只會評估爲the_list。它相當於:

if sentence: 
    self.sentence = sentence 
else: 
    self.sentence = ""