2016-08-27 1 views
-6

http://i.stack.imgur.com/IB0Yq.pngなぜPythonは私にこの関数のTypeErrorを与えますか? (コーディングの初心者)

コーディングが新しく、リストがタプルとして入力されている理由がわかりません。

+1

代わりに画像を追加するのでは追加する必要がありますソースコードは直接質問に。 –

+3

コードを表示するために画像を使用しないでください。あなたはあなたの質問をここにコピーして貼り付けるようにあなたの質問を編集することができます –

+2

そして、エラーが何を言っているか考えてみてください。リストにタプルを追加することはできません。とにかく、変数の型がそれ自身ではないので、 'type(list)is list'は間違っています...基本的には、' list'のようなPythonのデータ型や関数で変数名を指定しないでください –

答えて

4

組み込みタイプとローカル変数の両方に同じ名前listを使用しました。ビルトイン名を再使用しないでください。 PEP-8引用:予約されたキーワードを持つ関数の引数の名前が衝突した場合

を、むしろ、略語やスペルの破損を使用するよりも、単一の末尾のアンダースコアを付加することが一般的に優れています。したがってclass_clssより優れています。 (おそらく、より良いシノニムを使用することによって、このような衝突を避けるためです。)

試してみてください。

def funct2(list_): 
    if type(list_) == list: 
     ... 

それとも、より良い:

def funct2(list_): 
    if isinstance(list_, list): 
     ... 
0
def function2(list_variable): 
    #: dont use names that can shadow built in types 
    #: like `int`, `list` etc 

    if isinstance(list_variable, list): 
     #: do something here 
     list_variable.append(["a"]) #: to append a list i.e. ['b', ['a']] 
     list_variable + ["a"] #: also works but... `your cup of tea` 
    elif isinstance(list_variable, tuple): 
     #: you are trying to add a list `[]` to a tuple `("a",)` 

     #: this is not allowed, how does the computer know if it is to 
     #: convert your list to a tuple or your tuple to a list. 
     #: this conversion is called coercion look it up 
     #: Also read about immutability 
     list_variable + ("a",) 

    else: 
     print("Sorry, only lists or tuples allowed") 
関連する問題