【问题标题】:TypeError: coercing to Unicode: need string or buffer, property foundTypeError:强制转换为 Unicode:需要字符串或缓冲区,找到属性
【发布时间】:2018-10-15 22:19:10
【问题描述】:

我收到错误消息:“TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到属性”。我不确定这种通过属性提供信息的方式有什么问题

MainApp.py的相关代码

from constantsconfig import _Const

if not os.path.exists(_Const.CONFIG_DIRECTORY): //error happens on this line
    os.makedirs(_Const.CONFIG_DIRECTORY)

constantsconfig.py的相关代码

import os

def constant(f):
    def fset(self, value):
        raise TypeError
    def fget(self):
        return f()
    return property(fget, fset)

class _Const(object):
    @constant
    def MAIN_CRON_JOB_ID(self):
        return "MAIN_CRON_JOB_ID"
    @constant
    def DOWNLOAD_PHOTOS_INTERVAL_IN_MINUTES(self):
        return 15
    @constant
    def BASE_API_URL(self):
        return "http://example.com/file.php"
    @constant
    def API_KEY_RASPBERRIES(self):
        return "fasd79f97fsfa80f809f809fasd890fsda76fds5f54ds465fdas456"

错误信息

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2018.1\helpers\pydev\pydevd.py", line 1664, in <module>
    main()
  File "C:\Program Files\JetBrains\PyCharm 2018.1\helpers\pydev\pydevd.py", line 1658, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2018.1\helpers\pydev\pydevd.py", line 1068, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/_Data_/MainApp/RaspberriPi/_App/mainapp.py", line 192, in <module>
    if not os.path.exists(_Const.CONFIG_DIRECTORY):
  File "C:\_Data_\MainApp\RaspberriPi\_App\venv\lib\genericpath.py", line 26, in exists
    os.stat(path)
TypeError: coercing to Unicode: need string or buffer, property found

【问题讨论】:

  • 试试_Const().CONFIG_DIRECTORY
  • 嗯,成功了,我(还)不太熟悉python,一旦你知道就这么简单

标签: python python-2.7


【解决方案1】:

您正在使用类_Const。这是错误的,您应该使用_Const 类的实例

例如,

const = _Const()
if not os.path.exists(const.CONFIG_DIRECTORY):
    os.makedirs(const.CONFIG_DIRECTORY)

或者更好,

const = _Const()
try:
    os.mkdir(const.CONFIG_DIRECTORY)
except FileExistsError:
    pass

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 2015-02-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多