相关疑难解决方法(0)

TypeError:'function'对象不可订阅 - Python

我试图用这段代码解决一项任务:

bank_holiday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bank_holiday[month])

bank_holiday(int(input("Which month would you like to check out: ")))
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我收到错误:

TypeError: 'function' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

我不明白这是从哪里来的......

python

8
推荐指数
1
解决办法
6万
查看次数

重新定义python内置函数

我正在使用python程序,作者编写了一个看起来像这样的函数

def blah():
    str = "asdf asdf asdf"
    doStuff(str)
Run Code Online (Sandbox Code Playgroud)

即使str是内置函数,也不应将其用作变量,这似乎可行。

这里到底发生了什么?我的猜测是str将不再可用作函数,而只能在他编写的blah()函数的范围内使用。那是对的吗?这不会在全球范围内重新定义str,对吗?

python python-2.7

5
推荐指数
2
解决办法
5303
查看次数

遮蔽内置类型/函数的后果

我想知道重用内置类型或函数名称可能会产生什么后果.为了说明我的意思,请阅读以下示例:

list()是一个内置的功能.如果我创建另一个list()方法,我认为它将覆盖原始方法,以便执行我的而不是内置的方法.但如果我这样做会发生什么list=[a,z,e,r,t,y]?是否存在内置list类型或list()功能的风险?

我知道做这样的事情并不好.但我的目标只是了解在这些情况下会发生什么......

python built-in

4
推荐指数
1
解决办法
668
查看次数

UnboundLocalError:在赋值之前引用的局部变量....

import hmac, base64, hashlib, urllib2
base = 'https://.......'

def makereq(key, secret, path, data):
    hash_data = path + chr(0) + data
    secret = base64.b64decode(secret)
    sha512 = hashlib.sha512
    hmac = str(hmac.new(secret, hash_data, sha512))

    header = {
        'User-Agent': 'My-First-test',
        'Rest-Key': key,
        'Rest-Sign': base64.b64encode(hmac),
        'Accept-encoding': 'GZIP',
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    return urllib2.Request(base + path, data, header)
Run Code Online (Sandbox Code Playgroud)

错误:文件"C:/Python27/btctest.py",第8行,在makereq中hmac = str(hmac.new(secret,hash_data,sha512))UnboundLocalError:在赋值之前引用的局部变量'hmac'

有人知道为什么吗?谢谢

python python-2.7

4
推荐指数
2
解决办法
1万
查看次数

如何修复str的重新定义?

尝试使用Python解释器,我无意中分配了一个字符串,str如下所示:

str = 'whatever'
Run Code Online (Sandbox Code Playgroud)

后来在同一场会议上,我打电话给另一个声明str(),说......

double_whatever = str(2) + ' * whatever'
Run Code Online (Sandbox Code Playgroud)

...,并得到错误TypeError: 'str' object is not callable(而不是预期的输出'2 * whatever').一个相关的SO答案帮助我快速看到了我犯的错误.

但是,我仍然不清楚如何str()在受影响的会话中修复呼叫.当然我可以退出Python解释器并启动另一个会话,但我很好奇如何避免这种情况.

到目前为止,我已确认......

double_whatever = __builtins__.str(2) + ' * whatever'  # => '2 * whatever'
Run Code Online (Sandbox Code Playgroud)

...仍然像我想要的那样工作; 但我不清楚如何回到不需要__builtins__.资格.

如何修复我无意识的重新定义,str以便我str()在Python-interpreter会话中的调用再次起作用?

python string

4
推荐指数
1
解决办法
498
查看次数

在Python中测试变量类型

我正在为'Room'类创建一个初始化函数,并发现该程序不接受我对输入变量进行的测试.

为什么是这样?

def __init__(self, code, name, type, size, description, objects, exits):
    self.code = code
    self.name = name
    self.type = type
    self.size = size
    self.description = description
    self.objects = objects
    self.exits = exits
            #Check for input errors:
    if type(self.code) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 110'
    elif type(self.name) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 111'
    elif type(self.type) != type(str()):
        print 'Error found in module rooms.py!'
        print 'Error number: 112'
    elif type(self.size) …
Run Code Online (Sandbox Code Playgroud)

python testing variables

3
推荐指数
2
解决办法
2万
查看次数

python:UnboundLocalError:赋值前引用的局部变量'open'

def read_lines():
    readFileName = "readfile.txt"
    f = open(readFileName, 'r+')
    contents = f.read()
        ... # and so on 

read_lines()
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到一个错误:

f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
1
解决办法
4450
查看次数

'str'对象不可调用,如何处理?

当我运行我的Python Django应用程序时,我收到一个错误:

'str'对象不可调用

我在这里尝试了解决方案:TypeError:'str'对象不可调用(Python),但它们对我不起作用.我正在尝试运行Django书籍样本:

view.py:

# Create your views here.
from django.http import HttpResponse
import datetime

def current_time(request):
    now = datetime.datetime.now()
    html = "<html><head></head><body>%s</body></html>" % str(now)
    return HttpResponse(html)

def hello(request,name):
    return HttpResponse("Hello django")

def what(request):
    return HttpResponse("what's the problem django?")
Run Code Online (Sandbox Code Playgroud)

urls.py:

from django.conf.urls import patterns, include, url
from hello_django.views import current_time,hello,what


urlpatterns = patterns('',
    url(r'^time/$','current_time'),
    url(r'^what/$','what'),
    url(r'^hello/([a-zA-Z0-9]+)','hello'),
)
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试的网址:http://127.0.0.1:8000/what/.

堆栈跟踪:

TypeError at /what/
'str' object is not callable
Request Method: GET
Request URL:    http://127.0.0.1:8000/what/
Django Version: …
Run Code Online (Sandbox Code Playgroud)

python django

2
推荐指数
1
解决办法
2703
查看次数

Python:AttributeError:'str'对象没有属性'datetime'

我正在使用此代码:

def calcDateDifferenceInMinutes(end_date,start_date):
    fmt = '%Y-%m-%d %H:%M:%S'
    start_date_dt = datetime.strptime(start_date, fmt)
    end_date_dt = datetime.strptime(end_date, fmt)

# convert to unix timestamp
start_date_ts = time.mktime(start_date_dt.timetuple())
end_date_ts   = time.mktime(end_date_dt.timetuple())

# they are now in seconds, subtract and then divide by 60 to get minutes.
return (int(end_date_ts-start_date_ts) / 60)
Run Code Online (Sandbox Code Playgroud)

来自这个问题:stackoverflow问题

但我收到这条消息:

AttributeError:'str'对象没有属性'datetime'

我已经回顾了类似的问题但除了做以下事情之外没有看到任何其他选择:

start_date_dt = datetime.datetime.strptime(start_date, fmt)
Run Code Online (Sandbox Code Playgroud)

这是完整的痕迹:

> Traceback (most recent call last):   File "tabbed_all_cols.py", line
> 156, in <module>
>     trip_calculated_duration = calcDateDifferenceInMinutes (end_datetime,start_datetime)   File "tabbed_all_cols.py", line 41, in
> calcDateDifferenceInMinutes …
Run Code Online (Sandbox Code Playgroud)

python strptime

2
推荐指数
1
解决办法
1万
查看次数

类型错误:'str' 对象不能用 input() 调用

我有以下代码,它应该询问用户 2 文件名。我在第二个函数中的 input() 出现错误,但在第一个函数中没有,我不明白......这是错误:

output = getOutputFile() File "splitRAW.py", line 22, in getOutputFile fileName = input("\t=> ") TypeError: 'str' object is not callable

# Loops until an existing file has been found
def getInputFile():
    print("Which file do you want to split ?")
    fileName = input("\t=> ")
    while 1:
        try:
            file = open(fileName, "r")
            print("Existing file, let's continue !")
            return(fileName)
        except IOError:
            print("No such existing file...")
            print("Which file do you want to split ?")
            fileName = input("\t=> ")

# Gets …
Run Code Online (Sandbox Code Playgroud)

python error-handling input

2
推荐指数
1
解决办法
6585
查看次数

在Python中将列表转换为元组

>>> list=['a','b']
>>> tuple=tuple(list)
>>> list.append('a')
>>> print(tuple)
('a', 'b')
>>> another_tuple=tuple(list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
Run Code Online (Sandbox Code Playgroud)

为什么我不能将列表'list'转换为元组?

python tuples list python-3.x

1
推荐指数
1
解决办法
6441
查看次数

TypeError:“ str”对象不可调用。即使没有所谓的“ str”

在我开始之前,还有许多其他确切的问题,但是没有一个答案足以解决我的问题。类/函数log.info('foo')运行一次,没有问题,但是第二次调用它得到了错误TypeError: 'str' object is not callable

我发现这个问题与我有相同的问题,但是我没有任何东西叫做str。我已经使用其他功能(例如战争)进行了测试。

我的代码:

import praw
import sys
import traceback
from accounts import *

class logging:

    def info(self, log):
        self.info = '\033[94m'
        self.rs = '\033[0m'
        print self.info, 'INFO: ', self.rs

    def warn(self, log):
        self.warn = '\033[93m'
        self.rs = '\033[0m'
        print self.warn, 'WARNING: ', self.log, self.rs

    def critical(self, log):
        self.critical = '\033[91m'
        self.rs = '\033[0m'
        print self.critical, 'CRITICAL: ', log, self.rs

def read_accounts():
    with open('accounts.py') as f:
        for i, l in enumerate(f): …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

0
推荐指数
1
解决办法
650
查看次数