棘手:'dict'对象不可调用

时间:2015-11-05 14:17:09

标签: python dictionary

这是一个棘手的错误,你可以使用Python进入字典:

dict = {'a':5,'c':5}
#Typing some codes

在程序的某个时刻,您决定创建一个空字典:

new_dic = dict()

你得到这个追溯:

Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'dict' object is not callable

你能否告诉我它是否是Python中的一个错误,或者我们在使用内置函数时必须小心,而不是先为一些变量指定它们的名字?

4 个答案:

答案 0 :(得分:10)

你遇到的是“阴影”。您已在某个名称空间(模块的全局名称空间或函数的本地名称空间)中创建了一个与内置dict类型同名的对象。这会阻止您以通常的方式访问内置dict

可以仍然可以通过更多的努力来实现它。 {2}中的builtins(或__builtin__)模块包含通常可直接访问的所有内置对象。因此,要制作空字典,您可以执行以下操作:

import builtins

dict = whatever

newdic = builtins.dict()

但是......避免为自己的对象使用名称dict可能是个更好的主意。

答案 1 :(得分:0)

问题是你的第一行是覆盖 dict 的内容。试试这个。

dictA = {'a':5,'c':5}
new_dic = dict()

你的问题就会消失。

答案 2 :(得分:0)

在Python中,函数(以及其他所有东西)都是第一类对象。所以Python正在解释你的调用:

dict() -> call value of variable "dict" as a function

在您的情况下,由于dict中存储的值不是代码,因此会出现异常。

这是一个快速举例说明如何使用这种方式调用函数。

>>> a = lambda x: x + 2
>>> a
<function <lambda> at 0x10116b230>
>>> a(3)
5
>>> a(7)
9

这里我在a中存储了一个lambda(匿名函数),然后我可以将其作为函数调用。

您还可以为变量分配函数,然后使用变量名称调用它。

def a(x):
    return x + 2

b = a
b(3)    # returns 5

您也可以将此模式与嵌套函数一起使用来创建闭包。

在任何情况下,如果你只是避免使用也是关键字或内置函数的变量名,你会更好。

https://docs.python.org/2.7/reference/lexical_analysis.html#identifiers

https://docs.python.org/2/library/functions.html

答案 3 :(得分:0)

这是一个阴影案例。分配会影响内置 $(function(){ var filemanager = $('.filemanager'), breadcrumbs = $('.breadcrumbs'), fileList = filemanager.find('.data'); // Start by fetching the file data from scan.php with an AJAX request $.get('scan.php', function(data) { var response = [data], currentPath = '', breadcrumbsUrls = []; var folders = [], files = []; // This event listener monitors changes on the URL. We use it to // capture back/forward navigation in the browser. $(window).on('hashchange', function(){ goto(window.location.hash); // We are triggering the event. This will execute // this function on page load, so that we show the correct folder: }).trigger('hashchange'); // Hiding and showing the search box filemanager.find('.search').click(function(){ var search = $(this); search.find('span').hide(); search.find('input[type=search]').show().focus(); }); // Listening for keyboard input on the search field. // We are using the "input" event which detects cut and paste // in addition to keyboard input. filemanager.find('input').on('input', function(e){ folders = []; files = []; var value = this.value.trim(); if(value.length) { filemanager.addClass('searching'); // Update the hash on every key stroke window.location.hash = 'search=' + value.trim(); } else { filemanager.removeClass('searching'); window.location.hash = encodeURIComponent(currentPath); } }).on('keyup', function(e){ // Clicking 'ESC' button triggers focusout and cancels the search var search = $(this); if(e.keyCode == 27) { search.trigger('focusout'); } }).focusout(function(e){ // Cancel the search var search = $(this); if(!search.val().trim().length) { window.location.hash = encodeURIComponent(currentPath); search.hide(); search.parent().find('span').show(); } }); // Clicking on folders fileList.on('click', 'li.folders', function(e){ e.preventDefault(); var nextDir = $(this).find('a.folders').attr('href'); if(filemanager.hasClass('searching')) { // Building the breadcrumbs breadcrumbsUrls = generateBreadcrumbs(nextDir); filemanager.removeClass('searching'); filemanager.find('input[type=search]').val('').hide(); filemanager.find('span').show(); } else { breadcrumbsUrls.push(nextDir); } window.location.hash = encodeURIComponent(nextDir); currentPath = nextDir; }); // Clicking on breadcrumbs breadcrumbs.on('click', 'a', function(e){ e.preventDefault(); var index = breadcrumbs.find('a').index($(this)), nextDir = breadcrumbsUrls[index]; breadcrumbsUrls.length = Number(index); window.location.hash = encodeURIComponent(nextDir); }); // Navigates to the given hash (path) function goto(hash) { hash = decodeURIComponent(hash).slice(1).split('='); if (hash.length) { var rendered = ''; // if hash has search in it if (hash[0] === 'search') { filemanager.addClass('searching'); rendered = searchData(response, hash[1].toLowerCase()); if (rendered.length) { currentPath = hash[0]; render(rendered); } else { render(rendered); } } // if hash is some path else if (hash[0].trim().length) { rendered = searchByPath(hash[0]); if (rendered.length) { currentPath = hash[0]; breadcrumbsUrls = generateBreadcrumbs(hash[0]); render(rendered); } else { currentPath = hash[0]; breadcrumbsUrls = generateBreadcrumbs(hash[0]); render(rendered); } } // if there is no hash else { currentPath = data.path; breadcrumbsUrls.push(data.path); render(searchByPath(data.path)); } } } // Splits a file path and turns it into clickable breadcrumbs function generateBreadcrumbs(nextDir){ var path = nextDir.split('/').slice(0); for(var i=1;i<path;i++){ path[i] = path[i-1]+ '/' +path[i]; } return path; } // Locates a file by path function searchByPath(dir) { var path = dir.split('/'), demo = response, flag = 0; for(var i=0;i<path.length;i++){ for(var j=0;j<demo.length;j++){ if(demo[j].name === path[i]){ flag = 1; demo = demo[j].items; break; } } } demo = flag ? demo : []; return demo; } // Recursively search through the file tree function searchData(data, searchTerms) { data.forEach(function(d){ if(d.type === 'folder') { searchData(d.items,searchTerms); if(d.name.toLowerCase().match(searchTerms)) { folders.push(d); } } else if(d.type === 'file') { if(d.name.toLowerCase().match(searchTerms)) { files.push(d); } } }); return {folders: folders, files: files}; } // Render the HTML for the file manager function render(data) { var scannedFolders = [], scannedFiles = []; if(Array.isArray(data)) { data.forEach(function (d) { if (d.type === 'folder') { scannedFolders.push(d); } else if (d.type === 'file') { scannedFiles.push(d); } }); } else if(typeof data === 'object') { scannedFolders = data.folders; scannedFiles = data.files; } // Empty the old result and make the new one fileList.empty().hide(); if(!scannedFolders.length && !scannedFiles.length) { filemanager.find('.nothingfound').show(); } else { filemanager.find('.nothingfound').hide(); } if(scannedFolders.length) { scannedFolders.forEach(function(f) { var itemsLength = f.items.length, name = escapeHTML(f.name), icon = '<span class="icon folder"></span>'; if(itemsLength) { icon = '<span class="icon folder full"></span>'; } if(itemsLength == 1) { itemsLength += ' item'; } else if(itemsLength > 1) { itemsLength += ' items'; } else { itemsLength = 'Leeg'; } var folder = $('<li class="folders"><a href="'+ f.path +'" title="'+ f.path +'" class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></a></li>'); folder.appendTo(fileList); }); } if(scannedFiles.length) { scannedFiles.forEach(function(f) { var fileSize = bytesToSize(f.size), name = escapeHTML(f.name), fileType = name.split('.'), icon = '<span class="icon file"></span>'; fileType = fileType[fileType.length-1]; icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>'; var file = $('<li class="files"><a href="'+ f.path+'" title="'+ f.path +'" class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></a></li>'); file.appendTo(fileList); }); } // Generate the breadcrumbs var url = ''; if(filemanager.hasClass('searching')){ url = '<span>Zoek resultaten: </span>'; //fileList.removeClass('animated'); } else { fileList.addClass('animated'); breadcrumbsUrls.forEach(function (u, i) { var name = u.split('/'); if (i !== breadcrumbsUrls.length - 1) { url += '<a href="'+u+'"><span class="folderName">' + name[name.length-1] + '</span></a> <span class="arrow">→</span> '; } else { url += '<span class="folderName">' + name[name.length-1] + '</span>'; } }); } breadcrumbs.text('').append(url); // Show the generated elements fileList.animate({'display':'inline-block'}); } // This function escapes special html characters in names function escapeHTML(text) { return text.replace(/\&/g,'&amp;').replace(/\</g,'&lt;').replace(/\>/g,'&gt;'); } // Convert file sizes from bytes to human readable units function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes === 0) return '0 Bytes'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } }); }); 类型:

dict

正如错误所描述的那样,>>> type(dict) <type 'type'> >>> dict = {'a':5,'c':5} >>> type(dict) <type 'dict'> istances不可调用。

内置的dict通常会发生同样的事情。