Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

random.choice input 3 args but error msg say 4 args given #3

Open
jcsky opened this issue Jun 16, 2016 · 0 comments
Open

random.choice input 3 args but error msg say 4 args given #3

jcsky opened this issue Jun 16, 2016 · 0 comments

Comments

@jcsky
Copy link

jcsky commented Jun 16, 2016

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請參考入口網頁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants