GVKun编程网logo

TypeError:“列表”对象在python中不可调用(python list对象不可调用)

79

在本文中,我们将详细介绍TypeError:“列表”对象在python中不可调用的各个方面,并为您提供关于pythonlist对象不可调用的相关解答,同时,我们也将为您带来关于'int'对象在pyth

在本文中,我们将详细介绍TypeError:“列表”对象在python中不可调用的各个方面,并为您提供关于python list对象不可调用的相关解答,同时,我们也将为您带来关于'int'对象在python中不可调用、django:TypeError:“ tuple”对象不可调用、Python Flask,TypeError:“ dict”对象不可调用、Python Pandas TypeError:“方法”对象在预处理数据中不可下标的有用知识。

本文目录一览:

TypeError:“列表”对象在python中不可调用(python list对象不可调用)

TypeError:“列表”对象在python中不可调用(python list对象不可调用)

我是Python的新手,并且正在学习教程。list本教程中有一个示例:

example = list(''easyhoss'')

现在,在教程中,example= [''e'',''a'',...,''s'']。但就我而言,我得到以下错误:

>>> example = list(''easyhoss'')Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: ''list'' object is not callable

答案1

小编典典

好像你已经用list指向类实例的相同名称遮盖了指向类的内置名称。这是一个例子:

>>> example = list(''easyhoss'')  # here `list` refers to the builtin class>>> list = list(''abc'')  # we create a variable `list` referencing an instance of `list`>>> example = list(''easyhoss'')  # here `list` refers to the instanceTraceback (most recent call last):File "<string>", line 1, in <module>TypeError: ''list'' object is not callable
  1. 我相信这是显而易见的。Python将对象名称(函数和类也是对象)存储在字典中(命名空间实现为字典),因此你可以在任何范围内重写几乎任何名称。它不会显示为某种错误。如你所知,Python强调“特殊情况不足以打破规则”。你面临的问题背后有两个主要规则。

命名空间。Python支持嵌套名称空间。从理论上讲,你可以无休止地嵌套名称空间。正如我已经提到的,名称空间基本上是名称和对相应对象的引用的字典。你创建的任何模块都有其自己的“全局”名称空间。实际上,它只是特定模块的本地名称空间。

  1. 范围界定。引用名称时,Python运行时会在本地名称空间(相对于引用)中查找该名称,如果该名称不存在,它将在更高级别的名称空间中重复该尝试。该过程将继续进行,直到没有更高的名称空间为止。在这种情况下,你会得到一个NameError。内置函数和类驻留在特殊的高级命名空间中__builtins__。如果你list在模块的全局命名空间中声明了一个命名的变量,则解释器将永远不会在更高级别的命名空间(即__builtins__)中搜索该名称。同样,假设你var在模块中的函数内部创建一个变量,并在模块中创建另一个变量var。然后,如果var在函数内部引用,则永远不会获得全局var,因为var本地名称空间中有一个-解释器无需在其他位置搜索它。

这是一个简单的例子。

    >>> example = list("abc") # Works fine    # Creating name "list" in the global namespace of the module    >>> list = list("abc")        >>> example = list("abc")      Traceback (most recent call last):      File "<stdin>", line 1, in <module>    TypeError: ''list'' object is not callable    # Python looks for "list" and finds it in the global namespace.     # But it''s not the proper "list".    # Let''s remove "list" from the global namespace    >>> del list    # Since there is no "list" in the global namespace of the module,    # Python goes to a higher-level namespace to find the name.     >>> example = list("abc") # It works.

因此,如你所见,Python内置函数没有什么特别的。你的情况仅仅是通用规则的示例。你最好使用IDE(例如带有Python插件的PyCharm或Atom的免费版本)来突出显示名称阴影,以避免此类错误。

你可能还想知道什么是“可调用的”,在这种情况下,你可以阅读以下文章:https : //stackoverflow.com/a/111255/3846213。list,是一个类,是可以调用的。调用类会触发实例构造和初始化。实例可能是可调用的,但list实例不是。如果你对类和实例之间的区别更加困惑,那么你可能想要阅读文档(非常方便,同一页面介绍了名称空间和作用域)。

如果你想进一步了解内建函数,请阅读Christian Dean的答案。

聚苯乙烯

当启动交互式Python会话时,你将创建一个临时模块。

'int'对象在python中不可调用

'int'对象在python中不可调用

如何解决''int''对象在python中不可调用?

您在实例上设置具有相同名称的属性:

self.withdraw = withdraw

您正在尝试调用的是该属性,而不是方法。Python不会区分方法和属性,它们也不位于单独的命名空间中。

为属性使用其他名称;withdrawn(退出的过去时)作为更好的属性名称浮现在脑海:

class Bank:
    def __init__(self, name, id, balance, withdrawn):
        self.name = name
        self.id = id
        self.balance = balance
        self.withdrawn = withdrawn
    def print_info(self):
        return "%s %d %d" % (self.name, self.id, self.balance)
    def withdraw(self):
        if self.withdrawn > self.balance:
            return "ERROR: Not enough funds for this transfer"
        elif self.withdrawn < self.balance and self.withdrawn >= 0:
            self.balance = self.balance - self.withdrawn
            return self.balance
        else:
            return "Not a legitimate amount of funds"

(我也纠正了一个错字;您曾balace在打算使用的位置使用过balance)。

解决方法

我得到了这个,我期望它在打印x.withdraw()时能打印410。

Kyle 12345 500
Traceback (most recent call last):
    File "bank.py",line 21,in <module>
        print x.withdraw()
TypeError: ''int'' object is not callable

这是我的代码:

class Bank:
    def __init__(self,name,id,balance,withdraw):
        self.name = name
        self.id = id
        self.balance = balance
        self.withdraw = withdraw
    def print_info(self):
        return "%s %d %d" % (self.name,self.id,self.balance)
    def withdraw(self):
        if self.withdraw > self.balance:
            return "ERROR: Not enough funds for this transfer"
        elif self.withdraw < self.balance and self.withdraw >= 0:
            self.balance = self.balace - self.withdraw
            return self.balance
        else:
            return "Not a legitimate amount of funds"

x = Bank("Kyle",12345,500,90)
print x.print_info()
print x.withdraw()

我是否需要在类本身中修复某些问题,或者我的方法调用有问题?

django:TypeError:“ tuple”对象不可调用

django:TypeError:“ tuple”对象不可调用

收到类型错误,“
tuple”对象不可调用。知道会是什么吗?(不要担心缩进。它会怪异地复制。)我正在尝试基于storeliquor的PackSize创建选择。

Views.py:

def storeliquor(request,store_id,liquor_id):        
a = StoreLiquor.objects.get(StoreLiquorID=liquor_id)
s = Store.objects.get(StoreID=store_id)
x = Order.objects.get(storeID=s,Active=True)
y = a.OffPremisePrice
c = a.BottleSize

g = request.POST.get('OrderAmount','')
b = a.PackSize
h = b*2
d = b*3
e = b*4
r = b*5
if c == "1750 ML":
    pack_size = (
        ('1','1')
        ('3','3')
        (b,b)
        (h,h)
        (d,d)
        (e,e)
        (r,r)
    )
elif c == "1000 ML":
    pack_size = (
        ('1','3')
        ('6','6')
        (b,r)
    )
elif c == "750 ML":
    pack_size = (
        ('1',h)
        (c,r)
    )     
elif c == "375 ML":
    pack_size = (
        ('3','6')
        ('12','12')
        (b,r)
    )        
elif c == "200 ML":
    pack_size = (
        ('12','24')
        ('24','24')
        (b,b)
        (c,c)
        (c,r)
    ) 
else:
    pack_size = (
        (b,r)
    )




if request.method == "POST":
    f = AddToOrderForm(request.POST)

    if f.is_valid():
        z = f.save(commit=False)
        z.TotalPrice = (float(y)) * (float(g))
        z.storeliquorID = a
        z.orderID = x

        z.save()

    return HttpResponseRedirect('/stores/get/%s' % store_id)

else:
    f = AddToOrderForm()
    f.fields['OrderAmount'].choices = pack_size      
args = {}


args['liquor'] = a
args['s'] = s
args['form'] = f

return render(request,'storeliquor.html',args)

模型文件:

class LiquorOrder(models.Model):

LiquorOrderID = models.AutoField(primary_key=True)
storeliquorID = models.ForeignKey(StoreLiquor)
orderID = models.ForeignKey(Order)
OrderAmount = models.CharField('Order Amount',max_length=3)
TotalPrice = models.DecimalField('Total Price',max_digits=5,decimal_places=2)
StorePrice = models.DecimalField('Store Price',decimal_places=2)

表格文件:

class AddToOrderForm(forms.ModelForm):

class Meta:
    model = LiquorOrder
    fields = ('OrderAmount','StorePrice')

Python Flask,TypeError:“ dict”对象不可调用

Python Flask,TypeError:“ dict”对象不可调用

遇到一个似乎很普遍的问题,但我已经完成了研究,并且看不到它在任何地方都被完全重新创建了。当我打印时json.loads(rety.text),我看到了所需的输出。但是,当我打电话给return时,它显示了这个错误。有任何想法吗?非常感谢您的帮助,谢谢。我正在使用Flask
MethodHandler

class MHandler(MethodView):
    def get(self):
        handle = ''
        tweetnum = 100

        consumer_token = '' 
        consumer_secret = ''
        access_token = '-'
        access_secret = ''

        auth = tweepy.OAuthHandler(consumer_token,consumer_secret)
        auth.set_access_token(access_token,access_secret)

        api  = tweepy.API(auth)

        statuses = api.user_timeline(screen_name=handle,count= tweetnum,include_rts=False)

        pi_content_items_array = map(convert_status_to_pi_content_item,statuses)
        pi_content_items = { 'contentItems' : pi_content_items_array }

        saveFile = open("static/public/text/en.txt",'a') 
        for s in pi_content_items_array: 
            stat = s['content'].encode('utf-8')
            print stat

            trat = ''.join(i for i in stat if ord(i)<128)
            print trat
            saveFile.write(trat.encode('utf-8')+'\n'+'\n')

        try:
            contentFile = open("static/public/text/en.txt","r")
            fr = contentFile.read()
        except Exception as e:
            print "ERROR: couldn't read text file: %s" % e
        finally:
            contentFile.close()
        return lookup.get_template("newin.html").render(content=fr)

    def post(self):
        try:
            contentFile = open("static/public/text/en.txt","r")
            fd = contentFile.read()
        except Exception as e:
            print "ERROR: couldn't read text file: %s" % e
        finally:
                contentFile.close()
        rety = requests.post('https://gateway.watsonplatform.net/personality-insights/api/v2/profile',auth=('---',''),headers = {"content-type": "text/plain"},data=fd
            )

        print json.loads(rety.text)
        return json.loads(rety.text)


    user_view = MHandler.as_view('user_api')
    app.add_url_rule('/results2',view_func=user_view,methods=['GET',])
    app.add_url_rule('/results2',methods=['POST',])

这是Traceback(请记住上面的结果在打印):

Traceback (most recent call last):
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1836,in __call__
    return self.wsgi_app(environ,start_response)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1820,in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1403,in handle_exception
    reraise(exc_type,exc_value,tb)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1817,in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1478,in full_dispatch_request
    response = self.make_response(rv)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/flask/app.py",line 1577,in make_response
    rv = self.response_class.force_type(rv,request.environ)
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/wrappers.py",line 841,in force_type
    response = BaseResponse(*_run_wsgi_app(response,environ))
  File "/Users/RZB/anaconda/lib/python2.7/site-packages/werkzeug/test.py",line 867,in run_wsgi_app
    app_rv = app(environ,start_response)

Python Pandas TypeError:“方法”对象在预处理数据中不可下标

Python Pandas TypeError:“方法”对象在预处理数据中不可下标

如何解决Python Pandas TypeError:“方法”对象在预处理数据中不可下标?

我正在做一个关于机器学习的项目“发动机的预测性维护”。 我收到以下错误:

TypeError: ''method'' object is not subscriptable in preprosing data
#getting max number of cycles performed by each engine

它在行中显示错误

rul =pd.DataFrame(dataset_test.groupby[''id''][''cycle''].max()).reset_index()

有人可以帮忙吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

我们今天的关于TypeError:“列表”对象在python中不可调用python list对象不可调用的分享已经告一段落,感谢您的关注,如果您想了解更多关于'int'对象在python中不可调用、django:TypeError:“ tuple”对象不可调用、Python Flask,TypeError:“ dict”对象不可调用、Python Pandas TypeError:“方法”对象在预处理数据中不可下标的相关信息,请在本站查询。

本文标签: