-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Labels
Description
Question
我在工作上是用 ruby,這幾天開始學python,有個狀況不太懂,想跟大家請教一下
想請問為什麼它說我給了4個 arguments?? 我看起來只給了3個args
事情是這樣的,我的 random.choice 寫錯了
但 error msg 的內容讓我很好奇,如下:
# 錯誤寫法
>>> random.choice(1,2,3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: choice() takes exactly 2 arguments (4 given)
我給了3個 arguments,error msg 卻說 4 given,why~?!!!
Answers
@raytong
random.choice 應該是 def choice(self, array), 所以比你原來的多了一個 argument
http://openhome.cc/Gossip/Python/Class.html
@d2207197
random 是 Random class 的 instance。所有 instance method 第一個參數是 self,會自動給。
建議用 ipython 來當 REPL 不要用 python,會好用很多。
在 ipython 上可用 ? 與 ?? 來查文件。以你的例子就是
import random radom.choice??
另外有 browser 的話可以用 jupyter notebook ,開發和測試。自己電腦懶得裝可以先到 https://tmpnb.org 玩
結論
原因在於 choice 的定義大概是像這樣
def deposit(self, array):
也是為什麼它只接受一個array,卻表示 choice() takes exactly 2 arguments
因為第一個 arg 是 self,會自動賦予
正確寫法
*正確寫法*
random.choice([1,2,3])
2要加入Slack Python討論channe請參考入口網頁