Меню

Str object has no attribute items ошибка

In the following code:

#!/usr/local/bin/python
import json

APPLICATION_NAME = 'cc9226315643df89-36bf02429075329d0ba36748360d050c'

HEADERS1 = json.dumps(dict(Destination = u"/api/af/latest/applications/%s/rulesets" % (APPLICATION_NAME)))
print "Headers1 is %s" % (HEADERS1)
HEADERS2 = {'Destination': '/api/af/latest/applications/%s/rulesets' % (APPLICATION_NAME)}
print "Headers2 is %s" % (HEADERS2)

I get the following output:

Headers1 is {"Destination": "/api/af/latest/applications/cc9226315643df89-36bf02429075329d0ba36748360d050c/rulesets"}
Headers2 is {'Destination': '/api/af/latest/applications/cc9226315643df89-36bf02429075329d0ba36748360d050c/rulesets'}

but when I try to use either HEADER1 or HEADER2 in a REST call using requests(), I get very different results:

SERVER_URL = 'http://1.1.33.109:8087%s' % (APP_PATH)
REQ_DATA = None
print "Headers are: ", HEADERS
print "SERVER_URL is: ", SERVER_URL
print "Request Data is:", REQ_DATA
print ""

RESPONSE = requests.request(
    'MOVE', 
    SERVER_URL, 
    auth = ('admin', 'admin'), 
    verify = False, 
    data = REQ_DATA,
    headers = HEADERS1 )     #<-- If I use HEADER1 it breaks, if I use HEADER2 it works
print "Move Ruleset back to the Application RESULT: %sn" % (RESPONSE)

I get the following with HEADER1:

Traceback (most recent call last):
   File "./myrest.py", line 234, in <module>
     headers = HEADERS1 )
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 44, in request
     return session.request(method=method, url=url, **kwargs)
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 324, in request
     prep = req.prepare()
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 223, in prepare
     p.prepare_headers(self.headers)
   File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 340, in prepare_headers
     headers = dict((name.encode('ascii'), value) for name, value in headers.items())
AttributeError: 'str' object has no attribute 'items'

If I use HEADER2 it executes cleanly:

Move Ruleset back to the Application RESULT: Response [200]

Can anyone explain what the differences are?

Dear lamourj @lamourj
I update the setuptools to latest version ( 39.2.0 py36_0 defaults) but it still fails.

File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 2085, in _load_module
self._scan_code(m, co, co_ast)
File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 2547, in _scan_code
self._process_imports(module)
File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 2746, in _process_imports
target_module = self._safe_import_hook(*import_info, **kwargs)[0]
File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 2224, in _safe_import_hook
target_attr_names=None, level=level, edge_attr=edge_attr)
File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 1425, in import_hook
target_module = self._load_tail(target_package, target_module_partname)
File «D:Anaconda3envsintellibsite-packagesPyInstallerlibmodulegraphmo
dulegraph.py», line 1638, in _load_tail
submodule = self._safe_import_module(head, mname, submodule)
File «D:Anaconda3envsintellibsite-packagesPyInstallerdependanalysis.py
«, line 260, in _safe_import_module
hook_module.pre_safe_import_module(hook_api)
File «D:Anaconda3envsintellibsite-packagesPyInstallerhookspre_safe_imp
ort_modulehook-setuptools.extern.six.moves.py», line 34, in pre_safe_import_mod
ule
for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: ‘str’ object has no attribute ‘items’

================================================

packages in environment at D:Anaconda3envsintel:

Name Version Build Channel

alabaster 0.7.11 py36_0 defaults
altgraph 0.15 py_0 conda-forge
altgraph 0.15
asn1crypto 0.24.0 py36_intel_1 [intel] intel
astroid 1.6.5 py36_0 defaults
babel 2.6.0 py36_0 defaults
backcall 0.1.0 py36_intel_0 [intel] intel
backports 1.0 py36_intel_6 [intel] intel
bleach 2.1.3 py36_intel_0 [intel] intel
bzip2 1.0.6 vc14_intel_14 [intel vc14] intel
ca-certificates 2018.4.16 0 conda-forge
certifi 2018.1.18 py36_intel_0 [intel] intel
cffi 1.11.5 py36_intel_1 [intel] intel
chardet 3.0.4 py36_intel_0 [intel] intel
cloudpickle 0.5.3 py36_0 defaults
colorama 0.3.9 py36_intel_0 [intel] intel
cryptography 2.2.2 py36_intel_1 [intel] intel
cycler 0.10.0 py36_intel_5 [intel] intel
cython 0.28.2 py36_intel_4 [intel] intel
daal 2018.0.3.20180405 0 intel
decorator 4.3.0 py36_intel_0 [intel] intel
distarray 0.6.0 py36_intel_4 [intel] intel
docutils 0.14 py36h6012d8f_0 defaults
entrypoints 0.2.3 py36_intel_0 [intel] intel
freetype 2.9 vc14_intel_1 [intel vc14] intel
future 0.16.0 py36_0 conda-forge
future 0.16.0
get_terminal_size 1.0.0 py36_intel_5 [intel] intel
hdf5 1.10.1 vc14_intel_0 [intel vc14] intel
html5lib 1.0.1 py36_intel_1 [intel] intel
icc_rt 2018.0.3 intel_0 [intel] intel
icu 58.2 vc14_0 [vc14] conda-forge
idna 2.6 py36_intel_0 [intel] intel
imagesize 1.0.0 py36_0 defaults
impi_rt 2018.0.3 intel_0 [intel] intel
intel-openmp 2018.0.3 0 defaults
intelpython 2018.0.3 0 intel
intelpython3_core 0.0.0.custom 0 intel
intelpython3_full 0.0.0.custom 0 intel
ipykernel 4.6.1 py36_intel_0 [intel] intel
ipyparallel 6.0.2 py36_intel_0 [intel] intel
ipython 6.3.1 py36_intel_1 [intel] intel
ipython_genutils 0.2.0 py36_intel_0 [intel] intel
ipywidgets 7.0.0 py36_intel_0 [intel] intel
isort 4.3.4 py36_0 defaults
jedi 0.12.0 py36_intel_0 [intel] intel
jinja2 2.9.6 py36_intel_0 [intel] intel
jpeg 9b vc14_2 [vc14] conda-forge
jsonschema 2.6.0 py36_intel_0 [intel] intel
jupyter 1.0.0 py36_intel_5 [intel] intel
jupyter_client 5.1.0 py36_intel_0 [intel] intel
jupyter_console 5.1.0 py36_intel_0 [intel] intel
jupyter_core 4.4.0 py36_intel_1 [intel] intel
kiwisolver 1.0.1 py36_1 intel
lazy-object-proxy 1.3.1 py36hd1c21d2_0 defaults
libpng 1.6.34 vc14_intel_1 [intel vc14] intel
llvm-meta 6.0.0 0 conda-forge
llvmlite 0.20.0 py36_intel_0 [intel] intel
m2w64-gcc-libgfortran 5.3.0 6 defaults
m2w64-gcc-libs 5.3.0 7 defaults
m2w64-gcc-libs-core 5.3.0 7 defaults
m2w64-gmp 6.1.0 2 defaults
m2w64-libwinpthread-git 5.0.0.4634.697f757 2 defaults
macholib 1.8 py_0 conda-forge
macholib 1.9
markupsafe 1.0 py36_intel_0 [intel] intel
matplotlib 2.2.2 np114py36_intel_1 [intel] intel
mccabe 0.6.1 py36hb41005a_1 defaults
menuinst 1.4.14 py36hfa6e2cd_0 defaults
mistune 0.7.4 py36_intel_1 [intel] intel
mkl 2018.0.3 1 defaults
mkl-devel 2018.0.1 h470d631_5 defaults
mkl-include 2017.0.4 intel_0 intel
mkl-lb 2017.0.3 intel_5 intel
mkl-lb-static 2017.0.3 intel_6 intel
mkl-mic 2017.0.4 intel_0 intel
mkl-mic-static 2017.0.4 intel_0 intel
mkl-rt 11.1 p0 defaults
mkl-static 2017.0.4 intel_0 intel
mkl_fft 1.0.2 np114py36_intel_0 [intel] intel
mkl_random 1.0.1 np114py36_intel_0 [intel] intel
mpi4py 3.0.0 py36_intel_0 [intel] intel
mpmath 1.0.0 py36_intel_0 [intel] intel
msgpack 0.5.6
msys2-conda-epoch 20160418 1 defaults
nbconvert 5.2.1 py36_intel_0 [intel] intel
nbformat 4.4.0 py36_intel_0 [intel] intel
nose 1.3.7 py36_intel_16 [intel] intel
notebook 5.2.2 py36_intel_0 [intel] intel
numba 0.35.0 py36_intel_0 [intel] intel
numexpr 2.6.4 np114py36_intel_0 [intel] intel
numpy 1.14.3 py36_intel_0 [intel] intel
numpydoc 0.8.0 py36_0 defaults
openmp 2017.0.4 intel_0 intel
openmp-mic 2017.0.4 intel_0 intel
openssl 1.0.2o vc14_intel_0 [intel vc14] intel
packaging 17.1 py36_0 defaults
pandas 0.22.0 np114py36_intel_4 [intel] intel
pandocfilters 1.4.1 py36_intel_0 [intel] intel
parso 0.2.0 py36_intel_0 [intel] intel
path.py 11.0.1 py36_intel_0 [intel] intel
patsy 0.5.0 py36_0 defaults
pefile 2017.11.5
pefile 2017.11.5 py_0 conda-forge
pickleshare 0.7.4 py36_intel_1 [intel] intel
pip 9.0.1 py36_intel_1 [intel] intel
pip 10.0.1
prompt_toolkit 1.0.15 py36_intel_0 [intel] intel
psutil 5.4.6 py36hfa6e2cd_0 defaults
pycodestyle 2.4.0 py36_0 defaults
pycosat 0.6.3 py36h413d8a4_0 defaults
pycparser 2.18 py36_intel_0 [intel] intel
pycrypto 2.6.1 py36hfa6e2cd_8 defaults
pydaal 2018.0.3.20180405 np114py36_intel_1 [intel] intel
pyflakes 2.0.0 py36_0 defaults
pygments 2.2.0 py36_intel_1 [intel] intel
PyInstaller 3.4.dev0+84c1aaf96
pylint 1.9.2 py36_0 defaults
pyopenssl 17.5.0 py36_intel_0 [intel] intel
pyparsing 2.2.0 py36_intel_0 [intel] intel
pypiwin32 223
pyqt 5.9.2 py36h1aa27d4_0 defaults
PyQt5 5.10.1
pyqt5-tools 5.9.0.1.2
pysocks 1.6.7 py36_intel_0 [intel] intel
pytables 3.4.2 np114py36_intel_4 [intel] intel
python 3.6.3 intel_12 [intel] intel
python-dateutil 2.6.0 py36_intel_3 [intel] intel
pytz 2018.4 py36_intel_0 [intel] intel
pywin32 223
pywin32 223 py36hfa6e2cd_1 defaults
pywin32-ctypes 0.1.2
pywinpty 0.5.4 py36_0 defaults
pyyaml 3.12 py36_intel_4 [intel] intel
pyzmq 16.0.2 py36_intel_4 [intel] intel
qt 5.9.6 vc14h62aca36_0 defaults
qtawesome 0.4.4 py36h5aa48f6_0 defaults
qtconsole 4.3.1 py36h99a29a9_0 defaults
qtpy 1.4.2 py36_0 defaults
requests 2.18.4 py36_intel_0 [intel] intel
rope 0.10.7 py36had63a69_0 defaults
scikit-learn 0.19.1 np114py36_intel_29 [intel] intel
scipy 1.0.1 np114py36_intel_3 [intel] intel
seaborn 0.8.1 py36h9b69545_0 defaults
setuptools 39.2.0
setuptools 39.2.0 py36_0 defaults
simplegeneric 0.8.1 py36_intel_5 [intel] intel
singledispatch 3.4.0.3 py36h17d0c80_0 defaults
sip 4.19.8 py36h6538335_0 defaults
sip 4.19.8
six 1.11.0 py36_2 intel
six 1.11.0
snowballstemmer 1.2.1 py36h763602f_0 defaults
sphinx 1.7.5 py36_0 defaults
sphinxcontrib 1.0 py36hbbac3d2_1 defaults
sphinxcontrib-websupport 1.1.0 py36_1 defaults
spyder 3.2.8 py36_0 defaults
sqlite 3.23.1 vc14_intel_0 [intel vc14] intel
statsmodels 0.9.0 py36_0 conda-forge
sympy 1.1.1 py36_intel_3 [intel] intel
tbb 2018.0.4 vc14_0 [vc14] intel
tbb4py 2018.0.4 py36_vc14_0 [vc14] intel
tcl 8.6.4 vc14_intel_19 [intel vc14] intel
testpath 0.3.1 py36_intel_0 [intel] intel
tk 8.6.4 vc14_intel_27 [intel vc14] intel
tornado 4.5.2 py36_intel_0 [intel] intel
traitlets 4.3.2 py36_intel_1 [intel] intel
urllib3 1.22 py36_intel_0 [intel] intel
vc 14.0 2 intel
vs2015_runtime 14.0.25420 intel_0 [intel] intel
wcwidth 0.1.7 py36_intel_5 [intel] intel
webencodings 0.5.1 py36_0 intel
wheel 0.31.0 py36_intel_0 [intel] intel
widgetsnbextension 3.2.0 py36_0 intel
win_inet_pton 1.0.1 py36_intel_0 [intel] intel
win_unicode_console 0.5 py36_intel_0 [intel] intel
wincertstore 0.2 py36_intel_0 [intel] intel
winpty 0.4.3 4 defaults
wrapt 1.10.11 py36he5f5981_0 defaults
xz 5.2.3 vc14_intel_1 [intel vc14] intel
zlib 1.2.11 vc14_intel_4 [intel vc14] intel

When working with Python, you may come across strings that look like dictionaries. If you try using the items() attribute on them, you will get the error “AttributeError: ‘str’ object has no attribute ‘items’” in Python. This article will explain how the error occurs and how to fix it.

The reason of this error

From the error message, you may somewhat understand the error. The error occurs because you apply the items attribute to a string while the attribute is only available to the dictionary data type.

Code:

string = '{"key1": "value1", "key2": "value2", "key3": "value3"}'
 
print(string.items())

Result:

Traceback (most recent call last):
   line 3, in <module>
    print(string.items())
AttributeError: 'str' object has no attribute 'items'

You may have misunderstood when seeing a string looking like a dictionary. Keep reading, and we will show you some common situations where you can make mistakes and solve them.

Solutions to the error

Because the items() attribute is only available in the dictionary objects. You must convert the string into a dictionary to apply the attribute. We will introduce you to two methods to transform a string into a dictionary.

Use the json.loads() function

You likely face the string like that when working with json format. In this case, use the loads() function to convert the json string into a dictionary. Take a look at the example below for more details. 

Code:

import json

jsonString = '{"key1": "value1", "key2": "value2", "key3": "value3"}'
 
# Transform the json string into a dictionary
myDict = json.loads(jsonString)
 
print("The type of myDict is:", type(myDict))
print(f"The dictionary's items are: n{myDict.items()}")

Result:

The type of myDict is: <class 'dict'>
The dictionary's items are: 
dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

Use the eval() function 

You also use the eval() function to convert a string into a dictionary. But if you work with json, do not use the eval() function, although they can convert the string into a dictionary.

Code:

string = '{"key1": "value1", "key2": "value2", "key3": "value3"}'
 
# Transform the string into a dictionary
myDict = eval(string)
 
print("The type of myDict is:", type(myDict))
print(f"The dictionary's items are: n{myDict.items()}")

Result:

The type of myDict is: <class 'dict'>
The dictionary's items are: 
dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

Summary

In summary, the error “AttributeError: ‘str’ object has no attribute ‘items’” in Python occurs when you apply the items() attribute to a string that looks like a dictionary. To eliminate the error, convert the string into a dictionary by the json.loads() function if you work with JSON or the eval() function when working with normal strings.

Maybe you are interested:

  • AttributeError: ‘str’ object has no attribute ‘get’ in Python
  • AttributeError: ‘str’ object has no attribute ‘loads’
  • AttributeError module ‘jwt’ has no attribute ‘encode’ in Python

My name is Robert Collier. I graduated in IT at HUST university. My interest is learning programming languages; my strengths are Python, C, C++, and Machine Learning/Deep Learning/NLP. I will share all the knowledge I have through my articles. Hope you like them.

Name of the university: HUST
Major: IT
Programming Languages: Python, C, C++, Machine Learning/Deep Learning/NLP

Программирование, Python, Учебный процесс в IT, Блог компании SkillFactory


Рекомендация: подборка платных и бесплатных курсов PR-менеджеров — https://katalog-kursov.ru/

image

Выяснить, что означают сообщения об ошибках Python, может быть довольно сложно, когда вы впервые изучаете язык. Вот список распространенных ошибок, которые приводят к сообщениям об ошибках во время выполнения, которые могут привести к сбою вашей программы.

1) Пропуск “:” после оператора if, elif, else, for, while, class или def. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Пример кода с ошибкой:

if spam == 42

    print('Hello!')

2) Использование = вместо ==. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

= является оператором присваивания, а == является оператором сравнения «равно». Пример кода с ошибкой:

if spam = 42:

    print('Hello!')

3) Использование неправильного количества отступов. (Сообщение об ошибке: «IndentationError: unexpected indent» и «IndentationError: unindent does not match any outer indentation level» и «IndentationError: expected an indented block»)

Помните, что отступ увеличивается только после оператора, оканчивающегося на “:” двоеточие, и впоследствии должен вернуться к предыдущему отступу.
Пример кода с ошибкой:

print('Hello!')

    print('Howdy!')

… еще:

if spam == 42:

    print('Hello!')

  print('Howdy!')

… еще:

if spam == 42:

print('Hello!')

4) Забыть вызвать len() в операторе цикла for. (Сообщение об ошибке: “TypeError: 'list' object cannot be interpreted as an integer”)

Обычно вы хотите перебирать индексы элементов в списке или строке, что требует вызова функции range(). Просто не забудьте передать возвращаемое значение len(someList) вместо передачи только someList.

Пример кода с ошикой:

spam = ['cat', 'dog', 'mouse']

for i in range(spam):

    print(spam[i])

(UPD: как некоторые указали, вам может понадобиться только for i in spam: вместо приведенного выше кода. Но вышесказанное относится к очень законному случаю, когда вам нужен индекс в теле цикла, а не только само значение.)

5) Попытка изменить строковое значение. (Сообщение об ошибке: “TypeError: 'str' object does not support item assignment”)

Строки являются неизменным типом данных. Пример кода с ошибкой:

spam = 'I have a pet cat.'

spam[13] = 'r'

print(spam)

Пример правильного варианта:

spam = 'I have a pet cat.'

spam = spam[:13] + 'r' + spam[14:]

print(spam)

6) Попытка объединить не строковое значение в строковое значение. (Сообщение об ошибке: “TypeError: Can't convert 'int' object to str implicitly”)

Пример кода с ошибкой:

numEggs = 12
print('I have ' + numEggs + ' eggs.')
Правильный вариант:
numEggs = 12
print('I have ' + str(numEggs) + ' eggs.')

… или:

numEggs = 12
print('I have %s eggs.' % (numEggs))

7) Пропуск кавычки, в начале или конце строкового значения. (Сообщение об ошибке: “SyntaxError: EOL while scanning string literal”)

Пример кода с ошикой:

print(Hello!')

… еще:

print('Hello!)
...еще:
myName = 'Al'
print('My name is ' + myName + . How are you?')

8) Опечатка в переменной или имени функции. (Сообщение об ошибке: “NameError: name 'fooba' is not defined”)

Пример кода с ошибкой:

foobar = 'Al'
print('My name is ' + fooba)
...еще:
spam = ruond(4.2)
...еще:
spam = Round(4.2)

9) Опечатка в названии метода. (Сообщение об ошибке: “AttributeError: 'str' object has no attribute 'lowerr'”)

Пример кода с ошибкой:

spam = 'THIS IS IN LOWERCASE.'
spam = spam.lowerr()

10) Выход за пределы массива. (Сообщение об ошибке: “IndexError: list index out of range”)

Пример кода с ошибкой:

spam = ['cat', 'dog', 'mouse']
print(spam[6])

11) Использование несуществующего ключа словаря. (Сообщение об ошибке: “KeyError: 'spam'”)

Пример кода с ошибкой:

spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'}
print('The name of my pet zebra is ' + spam['zebra'])

12) Попытка использовать ключевые слова Python в качестве переменной (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Ключевые слова Python (также называются зарезервированные слова) не могут быть использованы для названия переменных. Ошибка будет со следующим кодом:

class = 'algebra'

Ключевые слова Python 3: and, as, assert, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

13) Использование расширенного оператора присваивания для новой переменной. (Сообщение об ошибке: “NameError: name 'foobar' is not defined”)

Не думайте, что переменные начинаются со значения, такого как 0 или пустая строка. Выражение с расширенным оператором как spam += 1 эквивалентно spam = spam + 1. Это означает, что для начала в spam должно быть какое-то значение.

Пример кода с ошибкой:

spam = 0
spam += 42
eggs += 42

14) Использование локальных переменных (с таким же именем как и у глобальной переменной) в функции до назначения локальной переменной. (Сообщение об ошибке: “UnboundLocalError: local variable 'foobar' referenced before assignment”)

Использовать локальную переменную в функции, имя которой совпадает с именем глобальной переменной, довольно сложно. Правило таково: если переменной в функции когда-либо назначается что-то, она всегда является локальной переменной, когда используется внутри этой функции. В противном случае, это глобальная переменная внутри этой функции.
Это означает, что вы не можете использовать ее как глобальную переменную в функции до ее назначения.

Пример кода с ошибкой:

someVar = 42
def myFunction():
    print(someVar)
    someVar = 100
myFunction()

15) Попытка использовать range() для создания списка целых чисел. (Сообщение об ошибке: “TypeError: 'range' object does not support item assignment”)

Иногда вам нужен список целочисленных значений по порядку, поэтому range() кажется хорошим способом создать этот список. Однако вы должны помнить, что range() возвращает «объект диапазона», а не фактическое значение списка.

Пример кода с ошибкой:

spam = range(10)
spam[4] = -1
То что вы хотите сделать, выглядит так:
spam = list(range(10))
spam[4] = -1

(UPD: Это работает в Python 2, потому что Python 2’s range() возвращает список значений. Но, попробовав сделать это в Python 3, вы увидите ошибку.)

16) Нет оператора ++ инкремента или -- декремента. (Сообщение об ошибке: “SyntaxError: invalid syntax”)

Если вы пришли из другого языка программирования, такого как C++, Java или PHP, вы можете попытаться увеличить или уменьшить переменную с помощью ++ или --. В Python таких операторов нет.

Пример кода с ошибкой:

spam = 0
spam++
То что вы хотите сделать, выглядит так:
spam = 0
spam += 1

17) UPD: как указывает Luchano в комментариях, также часто забывают добавить self в качестве первого параметра для метода. (Сообщение об ошибке: «TypeError: TypeError: myMethod() takes no arguments (1 given)»)

Пример кода с ошибкой:

class Foo():
    def myMethod():
        print('Hello!')
a = Foo()
a.myMethod()

Краткое объяснение различных сообщений об ошибках приведено в Приложении D книги «Invent with Python».


image
Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:

  • Курс «Профессия Data Scientist» (24 месяца)
  • Курс «Профессия Data Analyst» (18 месяцев)
  • Курс «Python для веб-разработки» (9 месяцев)

Читать еще

  • 450 бесплатных курсов от Лиги Плюща
  • Бесплатные курсы по Data Science от Harvard University
  • 30 лайфхаков чтобы пройти онлайн-курс до конца
  • Самый успешный и самый скандальный Data Science проект: Cambridge Analytica

Я должен написать так называемый «Facharbeit», в котором я решил решить сложный вопрос теста (о котором, вероятно, мне придется задать вопросы позже). Итак, сначала мне пришлось вызвать окно tkinter, и я добавил метку следующим образом:

b = tkinter.Label(GUI,"Facharbeit:Bundeswettbewerbsaufgabe")
b.place(GUI,"top")
``
line 16, b = tkinter.Label(GUI,"Facharbeit:Bundeswettbewerbsaufgabe")
  File "C:UsersrebecAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 3148, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:UsersrebecAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 2569, in __init__
    classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
AttributeError: 'str' object has no attribute 'items'

Итак, я сделал ошибку в этой строке:

b = tkinter.Label(GUI,"Facharbeit:Bundeswettbewerbsaufgabe")

Но я не вижу там никаких ошибок, кто-нибудь может мне помочь?

1 ответ

Подпись tkinter.Label:

tkinter.Label(master=None, cnf={}, **kw)

Что вы сделали:

tkinter.Label(GUI, "Facharbeit:Bundeswettbewerbsaufgabe")

Поскольку вы передали оба аргумента позиционно, GUI соответствует master (хорошо), а "Fachar..." соответствует cnf (сокращение от конфигурации) — не подходит. На самом деле вы передали строку тому, что ожидает словарь, и он попытался получить .items() ее, отсюда и ошибка.

Либо сделайте:

tkinter.Label(GUI, {"text": "Facharbeit:Bundeswettbewerbsaufgabe"})

Или

tkinter.Label(GUI, text="Facharbeit:Bundeswettbewerbsaufgabe")

Где этот последний вариант благодаря этой части **kw; в документации указано, какие параметры вы можете передать в качестве аргумента ключевого слова:

STANDARD OPTIONS

    activebackground, activeforeground, anchor,
    background, bitmap, borderwidth, cursor,
    disabledforeground, font, foreground,
    highlightbackground, highlightcolor,
    highlightthickness, image, justify,
    padx, pady, relief, takefocus, text,      <-- text here!
    textvariable, underline, wraplength


3

Mustafa Aydın
5 Сен 2022 в 19:43

Avatar

I have this python code which seem very straight forward but when I try to load it I get an error as above. you can view the full error message below too. Please what am I doing wrong? Thanks you.

class label_maker(osv.osv):
_name = 'label.maker'
_columns = {
    'name': fields.char('Label Name',size=200,required=True, help='This is the name of the label'),
    'label_owner': fields.char('Company Name',size=200,select=True, help='selects the product on the order line'),
   #        'sequence': fields.integer('Sequence',size=128, required=True),
}
   label_maker()

   class product_product_inherit(osv.osv):
_name = 'product.product.inherit'
_inherit = 'product.product'
_columns = {
    'labelnid': fields.many2one('label.maker','Label',select=True, help='label name'),
}
   product_product_inherit()

   class order_line(osv.osv):
_name = 'order.line'
_inherit = 'sale.order.line'
_columns = {
    'order_line_label': fields.many2one('label.maker','Label',select=True, help='select the right label for the product and partner'),
     #      'order_line_label': fields.related('product_id','labelnid',type='many2one',string='Label' relation= 'label_maker',select=True, help='select the right label for the product and partner'),
}
   order_line()

   class order_line_picking_list(osv.osv):
_name = 'order.line.picking.list'
_inherit = 'stock.move'
_columns = {
    'picking_labels': fields.many2one('label.maker','Label',select=True, help='label for the product on the picking list'),
   #        'labels': fields.related('order_id','order_line_label',type='many2one', relation='label_maker', string='Label', select=True, help='label for the product on the picking list'),
}
   order_line_picking_list()

Client Traceback (most recent call last):
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcommonhttp.py», line 180, in dispatch
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcontrollersmain.py», line 1052, in call_button
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcontrollersmain.py», line 996, in call_common
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcontrollersmain.py», line 1010, in _call_kw
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcommonopenerplibmain.py», line 250, in proxy
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcommonopenerplibmain.py», line 117, in proxy
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcommonhttp.py», line 608, in send

Server Traceback (most recent call last):
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonswebcommonhttp.py», line 593, in send
File «C:Program Files (x86)OpenERP 6.1-1server.openerpnetsvc.py», line 360, in dispatch_rpc
File «C:Program Files (x86)OpenERP 6.1-1server.openerpserviceweb_services.py», line 572, in dispatch
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvosv.py», line 167, in execute_kw
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvosv.py», line 121, in wrapper
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvosv.py», line 176, in execute
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvosv.py», line 164, in execute_cr
File «C:Program Files (x86)OpenERP 6.1-1serveropenerpaddonsbasemodulewizardbase_module_upgrade.py», line 101, in upgrade_module
File «C:Program Files (x86)OpenERP 6.1-1server.openerppooler.py», line 39, in restart_pool
File «C:Program Files (x86)OpenERP 6.1-1server.openerpmodulesregistry.py», line 160, in new
File «C:Program Files (x86)OpenERP 6.1-1server.openerpmodulesloading.py», line 338, in load_modules
File «C:Program Files (x86)OpenERP 6.1-1server.openerpmodulesloading.py», line 253, in load_marked_modules
File «C:Program Files (x86)OpenERP 6.1-1server.openerpmodulesloading.py», line 167, in load_module_graph
File «C:Program Files (x86)OpenERP 6.1-1server.openerpmodulesregistry.py», line 97, in load
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvorm.py», line 919, in create_instance
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvorm.py», line 1048, in __init__
File «C:Program Files (x86)OpenERP 6.1-1server.openerposvorm.py», line 3255, in _inherits_check
AttributeError: ‘str’ object has no attribute ‘items’

2Ответы

Hi,
Modify inherits = ‘product.product’ by inherit = ‘product.product’
Bye

Hi ,

had the same problem. resulted in a fields.related option. removed the store=True. and it worked.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Storung motorsteuerung ошибка man
  • Stoneridge se5000 ошибка 000800