标签归档:attributeerror

AttributeError(“’str’对象没有属性’read’”)

问题:AttributeError(“’str’对象没有属性’read’”)

在Python中,我得到一个错误:

Exception:  (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)

给定python代码:

def getEntries (self, sub):
    url = 'http://www.reddit.com/'
    if (sub != ''):
        url += 'r/' + sub

    request = urllib2.Request (url + 
        '.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
    response = urllib2.urlopen (request)
    jsonofabitch = response.read ()

    return json.load (jsonofabitch)['data']['children']

此错误是什么意思,我怎么做导致此错误?

In Python I’m getting an error:

Exception:  (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)

Given python code:

def getEntries (self, sub):
    url = 'http://www.reddit.com/'
    if (sub != ''):
        url += 'r/' + sub

    request = urllib2.Request (url + 
        '.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
    response = urllib2.urlopen (request)
    jsonofabitch = response.read ()

    return json.load (jsonofabitch)['data']['children']

What does this error mean and what did I do to cause it?


回答 0

问题在于,对于json.load您,应该传递带有已read定义函数的对象之类的文件。因此,您可以使用json.load(response)json.loads(response.read())

The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).


回答 1

AttributeError("'str' object has no attribute 'read'",)

这就是说的意思:有人试图.read在给它的对象上找到一个属性,然后给它一个类型的对象str(即,给它一个字符串)。

错误发生在这里:

json.load (jsonofabitch)['data']['children']

好吧,您不在read任何地方寻找,因此它必须在json.load您调用的函数中发生(如完整的回溯所示)。这是因为json.load正在尝试提供给.read您的东西,但是却给了它jsonofabitch,该东西当前命名为字符串(通过调用.read来创建response)。

解决方案:不要.read自欺欺人。函数将执行此操作,并希望您response直接给它以使其可以执行操作。

您也可以通过阅读功能的内置Python文档(try help(json.load)或整个模块(try help(json))),或通过查看http://docs.python.org上这些功能的文档来解决此问题。

AttributeError("'str' object has no attribute 'read'",)

This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).

The error occurred here:

json.load (jsonofabitch)['data']['children']

Well, you aren’t looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonofabitch, which currently names a string (which you created by calling .read on the response).

Solution: don’t call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.

You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .


回答 2

如果收到这样的python错误:

AttributeError: 'str' object has no attribute 'some_method'

您可能通过用字符串覆盖对象意外地中毒了对象。

如何用几行代码在python中重现此错误:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

运行它,打印:

AttributeError: 'str' object has no attribute 'loads'

但是更改变量名的名称,它可以正常工作:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

当您尝试在字符串中运行方法时,导致此错误。字符串有几种方法,但是您没有调用。因此,停止尝试调用String未定义的方法,并开始寻找在何处毒害了对象。

If you get a python error like this:

AttributeError: 'str' object has no attribute 'some_method'

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python
import json
def foobar(json):
    msg = json.loads(json)

foobar('{"batman": "yes"}')

Run it, which prints:

AttributeError: 'str' object has no attribute 'loads'

But change the name of the variablename, and it works fine:

#!/usr/bin/env python
import json
def foobar(jsonstring):
    msg = json.loads(jsonstring)

foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.


回答 3

好的,这是旧线程了。我有一个相同的问题,我的问题是我用了json.load而不是json.loads

这样,json加载任何类型的字典都没有问题。

官方文件

json.load-使用此转换表将fp(支持.read()的文本文件或包含JSON文档的二进制文件)反序列化为Python对象。

json.loads-使用此转换表将s(包含JSON文档的str,字节或字节数组实例)反序列化为Python对象。

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load – Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads – Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.


回答 4

您需要先打开文件。这不起作用:

json_file = json.load('test.json')

但这有效:

f = open('test.json')
json_file = json.load(f)

You need to open the file first. This doesn’t work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)

__getattr__在模块上

问题:__getattr__在模块上

如何实现等效的 __getattr__在类,模块上于a?

当调用模块的静态定义的属性中不存在的函数时,我希望在该模块中创建一个类的实例,并使用与该模块上的属性查找失败相同的名称调用该方法。

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

# note this function is intentionally on the module, and not the class above
def __getattr__(mod, name):
    return getattr(A(), name)

if __name__ == "__main__":
    # i hope here to have my __getattr__ function above invoked, since
    # salutation does not exist in the current namespace
    salutation("world")

这使:

matt@stanley:~/Desktop$ python getattrmod.py 
Traceback (most recent call last):
  File "getattrmod.py", line 9, in <module>
    salutation("world")
NameError: name 'salutation' is not defined

How can implement the equivalent of a __getattr__ on a class, on a module?

Example

When calling a function that does not exist in a module’s statically defined attributes, I wish to create an instance of a class in that module, and invoke the method on it with the same name as failed in the attribute lookup on the module.

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

# note this function is intentionally on the module, and not the class above
def __getattr__(mod, name):
    return getattr(A(), name)

if __name__ == "__main__":
    # i hope here to have my __getattr__ function above invoked, since
    # salutation does not exist in the current namespace
    salutation("world")

Which gives:

matt@stanley:~/Desktop$ python getattrmod.py 
Traceback (most recent call last):
  File "getattrmod.py", line 9, in <module>
    salutation("world")
NameError: name 'salutation' is not defined

回答 0

不久前,Guido宣布对新型类的所有特殊方法查找都绕过__getattr__and__getattribute__。Dunder方法曾经工作的模块-你可以,例如,使用一个模块作为一个上下文管理器简单地通过定义__enter____exit__,这些技巧之前爆发

最近,一些历史功能已经卷土重来,其中的一个模块已被卷土重来,__getattr__因此,sys.modules不再需要现有的hack(在导入时将一个模块替换为一个类)。

在Python 3.7+中,您仅使用一种显而易见的方法。要自定义模块上的属性访问,请__getattr__在模块级别定义一个函数,该函数应接受一个参数(属性名称),然后返回计算值或引发一个AttributeError

# my_module.py

def __getattr__(name: str) -> Any:
    ...

这也将允许钩子插入“ from”导入,即,您可以为语句(例如)返回动态生成的对象 from my_module import whatever

与此相关的是,您还可以与模块getattr一起__dir__在模块级别定义一个函数以响应dir(my_module)。有关详细信息,请参见PEP 562

A while ago, Guido declared that all special method lookups on new-style classes bypass __getattr__ and __getattribute__. Dunder methods had previously worked on modules – you could, for example, use a module as a context manager simply by defining __enter__ and __exit__, before those tricks broke.

Recently some historical features have made a comeback, the module __getattr__ among them, and so the existing hack (a module replacing itself with a class in sys.modules at import time) should be no longer necessary.

In Python 3.7+, you just use the one obvious way. To customize attribute access on a module, define a __getattr__ function at the module level which should accept one argument (name of attribute), and return the computed value or raise an AttributeError:

# my_module.py

def __getattr__(name: str) -> Any:
    ...

This will also allow hooks into “from” imports, i.e. you can return dynamically generated objects for statements such as from my_module import whatever.

On a related note, along with the module getattr you may also define a __dir__ function at module level to respond to dir(my_module). See PEP 562 for details.


回答 1

您在这里遇到两个基本问题:

  1. __xxx__ 方法只在类上查找
  2. TypeError: can't set attributes of built-in/extension type 'module'

(1)表示任何解决方案还必须跟踪正在检查的模块,否则每个模块将具有实例替换行为;(2)表示(1)甚至是不可能的……至少不是直接的。

幸运的是,sys.modules对那里发生的事情并不挑剔,因此可以使用包装器,但是只能用于模块访问(即import somemodule; somemodule.salutation('world'),对于相同模块的访问,您几乎必须从替换类中提取方法并将其添加到globals()eiher中。类上的自定义方法(我喜欢使用.export())或具有泛型函数(例如已经列出的答案)要记住的一件事:如果包装器每次都创建一个新实例,而全局解决方案不是,最终,您的行为会有所不同。哦,您不能同时使用两者-一种是另一种。


更新资料

Guido van Rossum出发:

实际上,偶尔会使用并推荐一种hack:一个模块可以用所需的功能定义一个类,然后最后,用该类的实例(如果需要,可以用该类)替换sys.modules中的自身。 ,但通常用处不大)。例如:

# module foo.py

import sys

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>

sys.modules[__name__] = Foo()

之所以可行,是因为导入机制正在积极地启用此hack,并且在加载的最后一步是将实际模块从sys.modules中拉出。(这绝非偶然。黑客是在很久以前就提出的,我们认为我们很喜欢在进口机器中提供支持。)

因此,完成所需操作的既定方法是在模块中创建一个类,并且作为模块的最后一步,sys.modules[__name__]用您的类的实例替换-现在您可以根据需要使用__getattr__/ __setattr__/ __getattribute__进行操作。


注意1:如果您使用此功能,则在进行sys.modules分配时,模块中的所有其他内容(例如全局变量,其他函数等)都会丢失-因此请确保所需的所有内容都在替换类之内。

注意2:要支持from module import *您必须__all__在类中进行定义;例如:

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>
    __all__ = list(set(vars().keys()) - {'__module__', '__qualname__'})

根据您的Python版本,可能会省略其他名称__all__set()如果不需要Python 2兼容性,可以省略。

There are two basic problems you are running into here:

  1. __xxx__ methods are only looked up on the class
  2. TypeError: can't set attributes of built-in/extension type 'module'

(1) means any solution would have to also keep track of which module was being examined, otherwise every module would then have the instance-substitution behavior; and (2) means that (1) isn’t even possible… at least not directly.

Fortunately, sys.modules is not picky about what goes there so a wrapper will work, but only for module access (i.e. import somemodule; somemodule.salutation('world'); for same-module access you pretty much have to yank the methods from the substitution class and add them to globals() eiher with a custom method on the class (I like using .export()) or with a generic function (such as those already listed as answers). One thing to keep in mind: if the wrapper is creating a new instance each time, and the globals solution is not, you end up with subtly different behavior. Oh, and you don’t get to use both at the same time — it’s one or the other.


Update

From Guido van Rossum:

There is actually a hack that is occasionally used and recommended: a module can define a class with the desired functionality, and then at the end, replace itself in sys.modules with an instance of that class (or with the class, if you insist, but that’s generally less useful). E.g.:

# module foo.py

import sys

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>

sys.modules[__name__] = Foo()

This works because the import machinery is actively enabling this hack, and as its final step pulls the actual module out of sys.modules, after loading it. (This is no accident. The hack was proposed long ago and we decided we liked enough to support it in the import machinery.)

So the established way to accomplish what you want is to create a single class in your module, and as the last act of the module replace sys.modules[__name__] with an instance of your class — and now you can play with __getattr__/__setattr__/__getattribute__ as needed.


Note 1: If you use this functionality then anything else in the module, such as globals, other functions, etc., will be lost when the sys.modules assignment is made — so make sure everything needed is inside the replacement class.

Note 2: To support from module import * you must have __all__ defined in the class; for example:

class Foo:
    def funct1(self, <args>): <code>
    def funct2(self, <args>): <code>
    __all__ = list(set(vars().keys()) - {'__module__', '__qualname__'})

Depending on your Python version, there may be other names to omit from __all__. The set() can be omitted if Python 2 compatibility is not needed.


回答 2

这是一个技巧,但是您可以使用一个类包装模块:

class Wrapper(object):
  def __init__(self, wrapped):
    self.wrapped = wrapped
  def __getattr__(self, name):
    # Perform custom logic here
    try:
      return getattr(self.wrapped, name)
    except AttributeError:
      return 'default' # Some sensible default

sys.modules[__name__] = Wrapper(sys.modules[__name__])

This is a hack, but you can wrap the module with a class:

class Wrapper(object):
  def __init__(self, wrapped):
    self.wrapped = wrapped
  def __getattr__(self, name):
    # Perform custom logic here
    try:
      return getattr(self.wrapped, name)
    except AttributeError:
      return 'default' # Some sensible default

sys.modules[__name__] = Wrapper(sys.modules[__name__])

回答 3

我们通常不那样做。

我们要做的就是这个。

class A(object):
....

# The implicit global instance
a= A()

def salutation( *arg, **kw ):
    a.salutation( *arg, **kw )

为什么?使隐式全局实例可见。

例如,查看random模块,该模块创建一个隐式全局实例,以稍微简化您需要“简单”随机数生成器的用例。

We don’t usually do it that way.

What we do is this.

class A(object):
....

# The implicit global instance
a= A()

def salutation( *arg, **kw ):
    a.salutation( *arg, **kw )

Why? So that the implicit global instance is visible.

For examples, look at the random module, which creates an implicit global instance to slightly simplify the use cases where you want a “simple” random number generator.


回答 4

与@HåvardS提出的类似,在我需要在模块上实现一些魔术的情况下(例如__getattr__),我将定义一个继承types.ModuleType并放入其中的新类sys.modules(可能替换自定义模块ModuleType定义了定义)。

请参阅Werkzeug的主__init__.py文件,以实现此功能的强大功能。

Similar to what @Håvard S proposed, in a case where I needed to implement some magic on a module (like __getattr__), I would define a new class that inherits from types.ModuleType and put that in sys.modules (probably replacing the module where my custom ModuleType was defined).

See the main __init__.py file of Werkzeug for a fairly robust implementation of this.


回答 5

这有点黑,但是…

import types

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

    def farewell(self, greeting, accusative):
         print greeting, accusative

def AddGlobalAttribute(classname, methodname):
    print "Adding " + classname + "." + methodname + "()"
    def genericFunction(*args):
        return globals()[classname]().__getattribute__(methodname)(*args)
    globals()[methodname] = genericFunction

# set up the global namespace

x = 0   # X and Y are here to add them implicitly to globals, so
y = 0   # globals does not change as we iterate over it.

toAdd = []

def isCallableMethod(classname, methodname):
    someclass = globals()[classname]()
    something = someclass.__getattribute__(methodname)
    return callable(something)


for x in globals():
    print "Looking at", x
    if isinstance(globals()[x], (types.ClassType, type)):
        print "Found Class:", x
        for y in dir(globals()[x]):
            if y.find("__") == -1: # hack to ignore default methods
                if isCallableMethod(x,y):
                    if y not in globals(): # don't override existing global names
                        toAdd.append((x,y))


for x in toAdd:
    AddGlobalAttribute(*x)


if __name__ == "__main__":
    salutation("world")
    farewell("goodbye", "world")

通过遍历全局命名空间中的所有对象来工作。如果该项目是一个类,则在类属性上进行迭代。如果该属性是可调用的,则将其作为函数添加到全局命名空间中。

它忽略所有包含“ __”的属性。

我不会在生产代码中使用它,但是它应该可以帮助您入门。

This is hackish, but…

import types

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

    def farewell(self, greeting, accusative):
         print greeting, accusative

def AddGlobalAttribute(classname, methodname):
    print "Adding " + classname + "." + methodname + "()"
    def genericFunction(*args):
        return globals()[classname]().__getattribute__(methodname)(*args)
    globals()[methodname] = genericFunction

# set up the global namespace

x = 0   # X and Y are here to add them implicitly to globals, so
y = 0   # globals does not change as we iterate over it.

toAdd = []

def isCallableMethod(classname, methodname):
    someclass = globals()[classname]()
    something = someclass.__getattribute__(methodname)
    return callable(something)


for x in globals():
    print "Looking at", x
    if isinstance(globals()[x], (types.ClassType, type)):
        print "Found Class:", x
        for y in dir(globals()[x]):
            if y.find("__") == -1: # hack to ignore default methods
                if isCallableMethod(x,y):
                    if y not in globals(): # don't override existing global names
                        toAdd.append((x,y))


for x in toAdd:
    AddGlobalAttribute(*x)


if __name__ == "__main__":
    salutation("world")
    farewell("goodbye", "world")

This works by iterating over the all the objects in the global namespace. If the item is a class, it iterates over the class attributes. If the attribute is callable it adds it to the global namespace as a function.

It ignore all attributes which contain “__”.

I wouldn’t use this in production code, but it should get you started.


回答 6

这是我自己的不起眼的贡献-@HåvardS的高度评价的答案略有修饰,但略显一点(因此@ S.Lott可以接受,尽管可能对OP不够好):

import sys

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

class Wrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def __getattr__(self, name):
        try:
            return getattr(self.wrapped, name)
        except AttributeError:
            return getattr(A(), name)

_globals = sys.modules[__name__] = Wrapper(sys.modules[__name__])

if __name__ == "__main__":
    _globals.salutation("world")

Here’s my own humble contribution — a slight embellishment of @Håvard S’s highly rated answer, but a bit more explicit (so it might be acceptable to @S.Lott, even though probably not good enough for the OP):

import sys

class A(object):
    def salutation(self, accusative):
        print "hello", accusative

class Wrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def __getattr__(self, name):
        try:
            return getattr(self.wrapped, name)
        except AttributeError:
            return getattr(A(), name)

_globals = sys.modules[__name__] = Wrapper(sys.modules[__name__])

if __name__ == "__main__":
    _globals.salutation("world")

回答 7

创建包含您的类的模块文件。导入模块。getattr在刚导入的模块上运行。您可以使用以下方式进行动态导入__import__ sys.modules中的模块。

这是您的模块some_module.py

class Foo(object):
    pass

class Bar(object):
    pass

在另一个模块中:

import some_module

Foo = getattr(some_module, 'Foo')

动态地执行此操作:

import sys

__import__('some_module')
mod = sys.modules['some_module']
Foo = getattr(mod, 'Foo')

Create your module file that has your classes. Import the module. Run getattr on the module you just imported. You can do a dynamic import using __import__ and pull the module from sys.modules.

Here’s your module some_module.py:

class Foo(object):
    pass

class Bar(object):
    pass

And in another module:

import some_module

Foo = getattr(some_module, 'Foo')

Doing this dynamically:

import sys

__import__('some_module')
mod = sys.modules['some_module']
Foo = getattr(mod, 'Foo')

为什么Python 3.6.1抛出AttributeError:模块’enum’没有属性’IntFlag’?

问题:为什么Python 3.6.1抛出AttributeError:模块’enum’没有属性’IntFlag’?

我刚刚为MacOS X安装了Python 3.6.1

当我尝试运行控制台(或使用Python3运行任何命令)时,抛出此错误:

  AttributeError: module 'enum' has no attribute 'IntFlag'

$ /Library/Frameworks/Python.framework/Versions/3.6/bin/python3  
Failed to import the site module  
Traceback (most recent call last):  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 544, in <module>  
    main()  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 530, in main  
    known_paths = addusersitepackages(known_paths)  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 282, in addusersitepackages  
    user_site = getusersitepackages()  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 258, in getusersitepackages  
    user_base = getuserbase() # this will also set USER_BASE  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 248, in getuserbase  
    USER_BASE = get_config_var('userbase')  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 601, in get_config_var  
    return get_config_vars().get(name)  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 580, in get_config_vars  
    import _osx_support  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_osx_support.py", line 4, in <module>  
    import re  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 142, in <module>  
    class RegexFlag(enum.IntFlag):  
AttributeError: module 'enum' has no attribute 'IntFlag'  

IntFlag类存在于enum.py中。那么,为什么会抛出AttributeError?

I just installed Python 3.6.1 for MacOS X

When I attempt to run the Console(or run anything with Python3), this error is thrown:

  AttributeError: module 'enum' has no attribute 'IntFlag'

$ /Library/Frameworks/Python.framework/Versions/3.6/bin/python3  
Failed to import the site module  
Traceback (most recent call last):  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 544, in <module>  
    main()  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 530, in main  
    known_paths = addusersitepackages(known_paths)  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 282, in addusersitepackages  
    user_site = getusersitepackages()  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 258, in getusersitepackages  
    user_base = getuserbase() # this will also set USER_BASE  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site.py", line 248, in getuserbase  
    USER_BASE = get_config_var('userbase')  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 601, in get_config_var  
    return get_config_vars().get(name)  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sysconfig.py", line 580, in get_config_vars  
    import _osx_support  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/_osx_support.py", line 4, in <module>  
    import re  
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 142, in <module>  
    class RegexFlag(enum.IntFlag):  
AttributeError: module 'enum' has no attribute 'IntFlag'  

The class IntFlag exists within enum.py. So, why is the AttributeError being thrown?


回答 0

这是因为您enum不是标准库enum模块。您可能已经enum34安装了软件包。

检查是否属于这种情况的一种方法是检查物业 enum.__file__

import enum
print(enum.__file__)  
# standard library location should be something like 
# /usr/local/lib/python3.6/enum.py

从python 3.6开始,enum34库不再与标准库兼容。该库也是不必要的,因此您可以简单地将其卸载。

pip uninstall -y enum34

如果您需要代码在<= 3.4和> 3.4的python版本上运行,则可以enum-compat根据需要尝试。它仅enum34针对没有标准库枚举的python较旧版本安装。

It’s because your enum is not the standard library enum module. You probably have the package enum34 installed.

One way check if this is the case is to inspect the property enum.__file__

import enum
print(enum.__file__)  
# standard library location should be something like 
# /usr/local/lib/python3.6/enum.py

Since python 3.6 the enum34 library is no longer compatible with the standard library. The library is also unnecessary, so you can simply uninstall it.

pip uninstall -y enum34

If you need the code to run on python versions both <=3.4 and >3.4, you can try having enum-compat as a requirement. It only installs enum34 for older versions of python without the standard library enum.


回答 1

不知道您是否仍然有此问题。我遇到了类似的问题,只需取消设置即可解决PYTHONPATH

$ unset PYTHONPATH

Not sure whether you still have this issue. I had a similar issue and I was able to resolve it simply by unsetting PYTHONPATH

$ unset PYTHONPATH


回答 2

对我来说,此错误是在安装gcloud组件app-engine-python以便集成到pycharm后发生的。即使pycharm现在不上传到app-engine,卸载模块也有帮助。

For me this error occured after installing of gcloud component app-engine-python in order to integrate into pycharm. Uninstalling the module helped, even if pycharm is now not uploading to app-engine.


回答 3

如果有人在PyCharm中运行Google App Engine Python 3.7标准环境项目时由于遇到此错误而来这里,那么您所需要做的就是

  • 确保要运行的配置适用于Flask,而不适用于Google App Engine配置。
  • 然后在偏好设置>>语言和框架>> Google App Engine下禁用Google App Engine支持

原因是根据此链接

总体目标是您的应用程序应具有完全可移植性,并可以在任何标准Python环境中运行。您编写的是标准Python应用程序,而不是App Engine Python应用程序。作为此转变的一部分,您不再需要为应用程序的核心功能使用专有的App Engine API和服务。目前,Python 3.7运行时中不提供App Engine API。

我猜想当我们在PyCharm中将python 3.7项目创建为Google应用引擎项目时,它仍会尝试以与python2.7应用相同的方式进行操作

If anyone coming here because of getting this error while running a google app engine Python 3.7 standard environment project in PyCharm then all you need to do is

  • Make sure the configuration to run is for Flask, not Google App Engine configuration.
  • Then disable Google App Engine support under Preferences >> Languages & Framework >> Google App Engine

The reason being as per this link

The overall goal is that your app should be fully portable and run in any standard Python environment. You write a standard Python app, not an App Engine Python app. As part of this shift, you are no longer required to use proprietary App Engine APIs and services for your app’s core functionality. At this time, App Engine APIs are not available in the Python 3.7 runtime.

I guess when we create a python 3.7 project in PyCharm as a Google app engine project it still tries to do the same way it does for a python2.7 app


回答 4

免责声明:请@ juanpa.arrivillaga,如果您看到此答案,请随时写自己的答案,我将删除此帖子。

@ juanpa.arrivillaga 上面已经提到过

您的工作目录中是否有文件名enum.py?

这就是我遇到的问题。我当时还不知道python上的enum模块,并已命名我的测试文件enum.py

由于文件名模块名,因此存在冲突。有关模块的更多信息,请参见:https : //docs.python.org/2/tutorial/modules.html

DISCLAIMER: Please, @juanpa.arrivillaga, if you see this answer, feel free to write your own and I will remove this post.

@juanpa.arrivillaga had mentioned above:

Is there a file name enum.py in your working directory, by any chance?

This was the issue I encountered. I was not aware of the enum module on python at the time and had named my test file enum.py.

Since the file name is the module name, there was a conflict. More info on modules here: https://docs.python.org/2/tutorial/modules.html


回答 5

在pycharm首选项中禁用“ Google App Engine支持”对我来说解决了这个问题。

Disabling “Google App Engine Support” in pycharm preferences fixed this issue for me.


回答 6

HåkenLid的回答帮助解决了我的问题(谢谢!),在本例中,在运行于Docker容器中的Flask的Python3.7中FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7

就我而言,enum34是由另一个库(pip install smartsheet-python-sdk)安装的。对于那些遇到类似Docker容器问题的人,这是我的最终Dockerfile(跳至相关行):

FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7
...
RUN pip install -r requirements.txt
RUN pip uninstall -y enum34
...

Håken Lid’s answer helped solved my problem (thanks!) , in my case present in Python3.7 running Flask in a Docker container (FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7).

In my case, enum34 was being installed by another library (pip install smartsheet-python-sdk). For those coming with a similar Docker container problem, here is my final Dockerfile (stripped to the relevant lines):

FROM tiangolo/uwsgi-nginx-flask:python3.7-alpine3.7
...
RUN pip install -r requirements.txt
RUN pip uninstall -y enum34
...

回答 7

如果必须同时为python2和python3保留PYTHONPATH,则可以编写别名语句以在bash_profile中设置适当的PYTHONPATH:

在〜/ .bash_profile中,对PYTHONPATH2和PYTHONPATH3变量进行硬编码,并在其末尾添加以下别名:

alias python='export PYTHONPATH=${PYTHONPATH2};python'
alias python3='export PYTHONPATH=${PYTHONPATH3};python3'

python(指python2),因为我更经常使用python2。

In case you have to keep PYTHONPATH for both python2 and python3, you can write alias statements to set the proper PYTHONPATH in your bash_profile:

Hardcode your PYTHONPATH2, and PYTHONPATH3 variables in your ~/.bash_profile, and add the following aliases at the end of it:

alias python='export PYTHONPATH=${PYTHONPATH2};python'
alias python3='export PYTHONPATH=${PYTHONPATH3};python3'

My python (refers to python2) as I use python2 more often.


回答 8

每当我遇到这个问题时:

AttributeError:模块“枚举”没有属性“ IntFlag”

只需首先运行命令:

unset PYTHONPATH 

然后运行我想要的命令,然后在其中成功。

When ever I got this problem:

AttributeError: module ‘enum’ has no attribute ‘IntFlag’

simply first i run the command:

unset PYTHONPATH 

and then run my desired command then got success in that.


回答 9

使用pip install <required-library> --ignore-installed enum34
安装所需的库后,在构建过程中查找警告。我收到这样的错误:
Using legacy setup.py install for future, since package 'wheel' is not installed
ERROR: pyejabberd 0.2.11 has requirement enum34==1.1.2, but you'll have enum34 1.1.10 which is incompatible.

要解决此问题,请运行以下命令:pip freeze | grep enum34。这将为您提供已安装的enum34的版本。现在将其卸载,pip uninstall enum34然后重新安装所需的版本
pip install "enum34==1.1.20"

I did by using pip install <required-library> --ignore-installed enum34
Once your required library is installed, look for warnings during the build. I got an Error like this:
Using legacy setup.py install for future, since package 'wheel' is not installed
ERROR: pyejabberd 0.2.11 has requirement enum34==1.1.2, but you'll have enum34 1.1.10 which is incompatible.

To fix this issue now run the command: pip freeze | grep enum34. This will give you the version of the installed enum34. Now uninstall it by pip uninstall enum34 and reinstall the required version as
pip install "enum34==1.1.20"


回答 10

我的计算机上安装了Python 2和Python 3。由于某些奇怪的原因,当调用re模块时,我在Python 3的sys.path中也有一个指向Python2的sitepackage库目录的路径。如果我运行Python 3并导入枚举,print(enum.__file__)并且系统未显示此Python 2站点包路径。因此,一个非常粗糙和肮脏的技巧是直接修改导入枚举的模块(遵循回溯路径)并在导入枚举之前插入以下代码:

import sys
for i, p in enumerate(sys.path):
    if "python27" in p.lower() or "python2.7" in p.lower(): sys.path.pop(i)
import enum

那解决了我的问题。

I have Python 2 and Python 3 installed on my computer. For some strange reason I have in the sys.path of Python 3 also a path to the sitepackage library directory of Python2 when the re module is called. If I run Python 3 and import enum and print(enum.__file__) the system does not show this Python 2 path to site-packages. So a very rough and dirty hack is, to directly modify the module in which enum is imported (follow the traceback paths) and insert the following code just before importing enum:

import sys
for i, p in enumerate(sys.path):
    if "python27" in p.lower() or "python2.7" in p.lower(): sys.path.pop(i)
import enum

That solved my problem.


回答 11

安装enum34的1.1.8版本对我有用。

我能够通过向pyproject.toml添加enum34 =“ == 1.1.8”来解决此问题。显然enum34在v1.1.8中具有避免此错误的功能,但在v1.1.9 +中已退步。不过,这只是一种解决方法。更好的解决方案是使程序包使用环境标记,因此除非需要,您根本不需要安装enum34。

来源:https//github.com/python-poetry/poetry/issues/1122

Installing version 1.1.8 of enum34 worked for me.

I was able to fix this by adding enum34 = “==1.1.8” to pyproject.toml. Apparently enum34 had a feature in v1.1.8 that avoided this error, but this regressed in v1.1.9+. This is just a workaround though. The better solution would be for packages to use environment markers so you don’t have to install enum34 at all unless needed.

Source: https://github.com/python-poetry/poetry/issues/1122


回答 12

即使我在运行python -m grpc_tools.protoc –version时遇到了这个问题,也必须设置PYTHONPATH直到站点包并关闭所有命令提示符窗口,然后它才能工作。希望它对gRPC用户有所帮助。

Even I had this issue while running python -m grpc_tools.protoc –version Had to set the PYTHONPATH till site-packages and shutdown all the command prompt windows and it worked. Hope it helps for gRPC users.


回答 13

我在使用python3.8和tensorflow 2.2.0的虚拟环境内核中的jupyterlab的ubuntu20.04中遇到了这个问题。错误消息原为

 Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/__init__.py", line 2, in <module>
    from .connect import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/connect.py", line 13, in <module>
    from IPython.core.profiledir import ProfileDir
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/__init__.py", line 48, in <module>
    from .core.application import Application
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/core/application.py", line 23, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/__init__.py", line 1, in <module>
    from .traitlets import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 49, in <module>
    import enum
ImportError: No module named enum

问题是在/ usr / bin / python中的符号链接中指向python2。解:

cd /usr/bin/
sudo ln -sf python3 python

我希望python2快死了!马库斯Terveisin

I had this problem in ubuntu20.04 in jupyterlab in my virtual env kernel with python3.8 and tensorflow 2.2.0. Error message was

 Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/__init__.py", line 2, in <module>
    from .connect import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/ipykernel/connect.py", line 13, in <module>
    from IPython.core.profiledir import ProfileDir
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/__init__.py", line 48, in <module>
    from .core.application import Application
  File "/home/hu-mka/.local/lib/python2.7/site-packages/IPython/core/application.py", line 23, in <module>
    from traitlets.config.application import Application, catch_config_error
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/__init__.py", line 1, in <module>
    from .traitlets import *
  File "/home/hu-mka/.local/lib/python2.7/site-packages/traitlets/traitlets.py", line 49, in <module>
    import enum
ImportError: No module named enum

problem was that in symbolic link in /usr/bin/python was pointing to python2. Solution:

cd /usr/bin/
sudo ln -sf python3 python

Hopefully Python 2 usage will drop off completely soon.


回答 14

如果在运行时有这个问题测试PyCharm,确保第二个框选中的配置。

If you having this issue when running tests in PyCharm, make sure the second box is unchecked in the configurations.


回答 15

如果有人有试图从virtualenv中运行Jupyter内核的时候这个问题,只需添加正确的PYTHONPATHkernel.json您的virtualenv内核(Python 3的例子)的:

{
 "argv": [
  "/usr/local/Cellar/python/3.6.5/bin/python3.6",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3 (TensorFlow)",
 "language": "python",
 "env": {
     "PYTHONPATH":     "/Users/dimitrijer/git/mlai/.venv/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/lib-dynload:/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/site-packages"
}
}

If anyone is having this problem when trying to run Jupyter kernel from a virtualenv, just add correct PYTHONPATH to kernel.json of your virtualenv kernel (Python 3 in example):

{
 "argv": [
  "/usr/local/Cellar/python/3.6.5/bin/python3.6",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}"
 ],
 "display_name": "Python 3 (TensorFlow)",
 "language": "python",
 "env": {
     "PYTHONPATH":     "/Users/dimitrijer/git/mlai/.venv/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/lib-dynload:/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6:/Users/dimitrijer/git/mlai/.venv/lib/python3.6/site-packages"
}
}

AttributeError:“模块”对象没有属性

问题:AttributeError:“模块”对象没有属性

我有两个python模块:

py

import b

def hello():
  print "hello"

print "a.py"
print hello()
print b.hi()

b.py

import a

def hi():
  print "hi"

当我跑步时a.py,我得到:

AttributeError: 'module' object has no attribute 'hi'

错误是什么意思?我如何解决它?

I have two python modules:

a.py

import b

def hello():
  print "hello"

print "a.py"
print hello()
print b.hi()

b.py

import a

def hi():
  print "hi"

When I run a.py, I get:

AttributeError: 'module' object has no attribute 'hi'

What does the error mean? How do I fix it?


回答 0

您有相互的顶级导入,这几乎总是一个坏主意。

如果您确实必须在Python中进行相互导入,则可以通过在函数中导入它们来实现:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

现在,a.py可以安全地进行操作import b而不会引起问题。

(乍看之下,cause_a_to_do_something()效率似乎很低,因为import每次调用它都会这样做,但是实际上导入工作只是第一次完成。第二次及以后的导入模块是一种快速的操作。 )

You have mutual top-level imports, which is almost always a bad idea.

If you really must have mutual imports in Python, the way to do it is to import them within a function:

# In b.py:
def cause_a_to_do_something():
    import a
    a.do_something()

Now a.py can safely do import b without causing problems.

(At first glance it might appear that cause_a_to_do_something() would be hugely inefficient because it does an import every time you call it, but in fact the import work only gets done the first time. The second and subsequent times you import a module, it’s a quick operation.)


回答 1

在不经意地将模块命名为与标准Python模块之一相同的模块时,我也看到了此错误。例如,我有一个名为的模块commands,它也是一个Python库模块。由于它无法在我的本地开发环境中正常运行,因此很难追踪,但是在Google App Engine上运行时由于指定的错误而失败。

I have also seen this error when inadvertently naming a module with the same name as one of the standard Python modules. E.g. I had a module called commands which is also a Python library module. This proved to be difficult to track down as it worked correctly on my local development environment but failed with the specified error when running on Google App Engine.


回答 2

问题在于模块之间的循环依赖关系。a进口bb进口a。但是其中一个需要首先被加载-在这种情况下,python最终在初始化模块a之前结束了bb.hi()当您尝试在python 中访问它时它尚不存在a

The problem is the circular dependency between the modules. a imports b and b imports a. But one of them needs to be loaded first – in this case python ends up initializing module a before b and b.hi() doesn’t exist yet when you try to access it in a.


回答 3

我通过引用以错误方式导入的枚举而收到此错误,例如:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

正确导入:

from package.MyEnumClass import MyEnumClass

希望对某人有帮助

I got this error by referencing an enum which was imported in a wrong way, e.g.:

from package import MyEnumClass
# ...
# in some method:
return MyEnumClass.Member

Correct import:

from package.MyEnumClass import MyEnumClass

Hope that helps someone


回答 4

我遇到了此错误,因为实际上未导入模块。代码如下:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

最后一行导致AttributeError。原因是我没有注意到aa.ba.c)的子模块已显式导入,并假定该import语句实际上是导入的a

I experienced this error because the module was not actually imported. The code looked like this:

import a.b, a.c

# ...

something(a.b)
something(a.c)
something(a.d)  # My addition, which failed.

The last line resulted in an AttributeError. The cause was that I had failed to notice that the submodules of a (a.b and a.c) were explicitly imported, and assumed that the import statement actually imported a.


回答 5

我遇到了同样的问题。使用修复reload

import the_module_name
from importlib import reload
reload(the_module_name)

I faced the same issue. fixed by using reload.

import the_module_name
from importlib import reload
reload(the_module_name)

回答 6

当我从git中检出较旧版本的存储库时遇到了这个问题。Git替换了我的.py文件,但保留了未跟踪的.pyc文件。由于.py文件和.pyc文件不同步,因此文件中的import命令.py无法在文件中找到相应的模块.pyc

解决方案就是删除.pyc文件,然后让它们自动重新生成。

I ran into this problem when I checked out an older version of a repository from git. Git replaced my .py files, but left the untracked .pyc files. Since the .py files and .pyc files were out of sync, the import command in a .py file could not find the corresponding module in the .pyc files.

The solution was simply to delete the .pyc files, and let them be automatically regenerated.


回答 7

ubuntu 18.04virtualenvpython.3.6.x)上,以下重新加载代码段为我解决了该问题:

main.py

import my_module  # my_module.py
from importlib import reload # reload 
reload(my_module)

print(my_module)
print(my_modeule.hello())

哪里:

|--main.py    
|--my_module.py

有关更多文档,请检查:这里

on ubuntu 18.04 ( virtualenv, python.3.6.x), the following reload snippet solved the problem for me:

main.py

import my_module  # my_module.py
from importlib import reload # reload 
reload(my_module)

print(my_module)
print(my_modeule.hello())

where:

|--main.py    
|--my_module.py

for more documentation check : here


回答 8

以上所有答案都很不错,但我想在此鸣叫。如果没有发现上述任何问题,请尝试清理您的工作环境。它为我工作。

All the above answers are great, but I’d like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.


回答 9

不知道如何,但是以下更改对我的问题进行了排序:

我的文件名和导入名称相同,例如,我的文件名为emoji.py,并且我尝试导入emoji。但是更改文件名解决了这个问题。

希望有帮助

Not sure how but the below change sorted my issue:

i was having the name of file and import name same for eg i had file name as emoji.py and i was trying to import emoji. But changing the name of file solved the issue .

Hope so it helps


回答 10

循环导入会引起问题,但是Python可以缓解这种问题。

问题是当您运行时python a.py,它会运行a.py但不会将其标记为模块导入。因此依次a.py->导入模块b->导入模块a->导入模块b。自从b导入以来,最后一次导入a-no操作,Python对此进行了防范。b现在是一个空模块。因此,当它执行时b.hi(),它什么也找不到。

请注意,b.hi()执行的是在a.py->模块b->模块a 期间执行的,而不是a.py直接执行。

在您的特定示例中,您只能python -c 'import a'在顶层运行,因此的第一次执行a.py被注册为导入模块。

Circular imports cause problems, but Python has ways to mitigate it built-in.

The problem is when you run python a.py, it runs a.py but not mark it imported as a module. So in turn a.py -> imports module b -> imports module a -> imports module b. The last import a no-op since b is currently being imported and Python guards against that. And b is an empty module for now. So when it executes b.hi(), it can’t find anything.

Note that the b.hi() that got executed is during a.py -> module b -> module a, not in a.py directly.

In your specific example, you can just run python -c 'import a' at top-level, so the first execution of a.py is registered as importing a module.


回答 11

订单进口的就是为什么我有问题的原因:

a.py

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py

from a import ProblemThing

class NewThing(ProblemThing):
    pass

只是它的外观的另一个示例,类似于RichieHindie的答案,但带有类。

The order of the importing was the reason why I was having issues:

a.py:

############
# this is a problem
# move this to below
#############
from b import NewThing

class ProblemThing(object):
    pass

class A(object):
   ###############
   # add it here
   # from b import NewThing
   ###############
   nt = NewThing()
   pass

b.py:

from a import ProblemThing

class NewThing(ProblemThing):
    pass

Just another example of how it might look, similar to RichieHindie’s answer, but with classes.


回答 12

我已经多次遇到这个问题,但是我并没有尝试更深入地研究它。现在我了解了主要问题。

这次我的问题是从不同的模块(例如以下)中导入序列化器(django和restframework):

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

# the line below was the problem 'srlzprod'
from products import serializers as srlzprod

我遇到这样的问题:

from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'

我要完成的工作如下:

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()

    # the nested relation of the line below
    product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)

因此,正如上面几行提到的解决方法(顶级导入)所述,我继续进行以下更改:

# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by 
product = serializers.SerializerMethodField()

# and create the following method and call from there the required serializer class
def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

因此,django runserver的执行没有问题:

./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...

System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.

代码行的最终状态如下:

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    product = serializers.SerializerMethodField()

    class Meta:
        model = mdlpri.CampaignsProducts
        fields = '__all__'

    def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

希望这对其他人有帮助。

问候,

I have crossed with this issue many times, but I didnt try to dig deeper about it. Now I understand the main issue.

This time my problem was importing Serializers ( django and restframework ) from different modules such as the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

# the line below was the problem 'srlzprod'
from products import serializers as srlzprod

I was getting a problem like this :

from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'

What I wanted to accomplished was the following :

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()

    # the nested relation of the line below
    product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)

So, as mentioned by the lines above how to solve it ( top-level import ), I proceed to do the following changes :

# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by 
product = serializers.SerializerMethodField()

# and create the following method and call from there the required serializer class
def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Therefore, django runserver was executed without problems :

./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...

System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.

Final state of the code lines was the following :

from rest_framework import serializers

from common import serializers as srlz
from prices import models as mdlpri

class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
    bank_name = serializers.CharField(trim_whitespace=True,)
    coupon_type = serializers.SerializerMethodField()
    promotion_description = serializers.SerializerMethodField()
    product = serializers.SerializerMethodField()

    class Meta:
        model = mdlpri.CampaignsProducts
        fields = '__all__'

    def get_product(self, obj):
        from products import serializers as srlzprod
        p_fields = ['id', 'name', ]
        return srlzprod.ProductsSerializers(
            obj.product, fields=p_fields, many=False,
        ).data

Hope this could be helpful for everybody else.

Greetings,


回答 13

就我而言,使用numpy版本1.15.0的python 2.7时,它与

pip install statsmodels=="0.10.0"

In my case working with python 2.7 with numpy version 1.15.0, it worked with

pip install statsmodels=="0.10.0"

为什么会出现AttributeError:’NoneType’对象没有属性’something’?

问题:为什么会出现AttributeError:’NoneType’对象没有属性’something’?

我不断收到错误消息,说

AttributeError: 'NoneType' object has no attribute 'something'

我的代码太长,无法在此处发布。什么一般情况会导致这种情况AttributeError,这NoneType意味着什么,我如何缩小正在发生的事情?

I keep getting an error that says

AttributeError: 'NoneType' object has no attribute 'something'

The code I have is too long to post here. What general scenarios would cause this AttributeError, what is NoneType supposed to mean and how can I narrow down what’s going on?


回答 0

NoneType意味着您实际上拥有了而不是您认为正在使用的任何Class或Object的实例None。这通常意味着在上面的赋值或函数调用失败或返回了意外结果。

NoneType means that instead of an instance of whatever Class or Object you think you’re working with, you’ve actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result.


回答 1

您有一个等于None的变量,并且您试图访问它的名为“ something”的属性。

foo = None
foo.something = 1

要么

foo = None
print foo.something

两者都会产生一个 AttributeError: 'NoneType'

You have a variable that is equal to None and you’re attempting to access an attribute of it called ‘something’.

foo = None
foo.something = 1

or

foo = None
print(foo.something)

Both will yield an AttributeError: 'NoneType'


回答 2

其他人则解释了什么NoneType是结束它的常见方法(即,无法从函数返回值)。

另一个None不希望看到的常见原因是在可变对象上分配了就地操作。例如:

mylist = mylist.sort()

sort()列表的方法对列表进行原位排序,mylist即被修改。但是该方法的实际返回值None不是对列表进行排序。因此,您刚刚分配Nonemylist。如果您下次尝试这样做,mylist.append(1)Python会给您这个错误。

Others have explained what NoneType is and a common way of ending up with it (i.e., failure to return a value from a function).

Another common reason you have None where you don’t expect it is assignment of an in-place operation on a mutable object. For example:

mylist = mylist.sort()

The sort() method of a list sorts the list in-place, that is, mylist is modified. But the actual return value of the method is None and not the list sorted. So you’ve just assigned None to mylist. If you next try to do, say, mylist.append(1) Python will give you this error.


回答 3

NoneType是该值的类型None。在这种情况下,变量lifetime的值为None

发生这种情况的一种常见方法是调用缺少a的函数return

但是,还有无数其他方法可以将变量设置为“无”。

The NoneType is the type of the value None. In this case, the variable lifetime has a value of None.

A common way to have this happen is to call a function missing a return.

There are an infinite number of other ways to set a variable to None, however.


回答 4

考虑下面的代码。

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

这会给你错误

AttributeError:“ NoneType”对象没有属性“ real”

所以要点如下。

  1. 在代码中,函数或类方法未返回任何内容或未返回None
  2. 然后,您尝试访问该返回对象的属性(即None),从而导致错误消息。

Consider the code below.

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

This is going to give you the error

AttributeError: ‘NoneType’ object has no attribute ‘real’

So points are as below.

  1. In the code, a function or class method is not returning anything or returning the None
  2. Then you try to access an attribute of that returned object(which is None), causing the error message.

回答 5

这意味着您正在尝试访问的对象NoneNoneNullpython中的变量。这种类型的错误发生在您的代码上,就像这样。

x1 = None
print(x1.something)

#or

x1 = None
x1.someother = "Hellow world"

#or
x1 = None
x1.some_func()

# you can avoid some of these error by adding this kind of check
if(x1 is not None):
    ... Do something here
else:
    print("X1 variable is Null or None")

It means the object you are trying to access None. None is a Null variable in python. This type of error is occure de to your code is something like this.

x1 = None
print(x1.something)

#or

x1 = None
x1.someother = "Hellow world"

#or
x1 = None
x1.some_func()

# you can avoid some of these error by adding this kind of check
if(x1 is not None):
    ... Do something here
else:
    print("X1 variable is Null or None")

回答 6

gddc是正确的,但添加了一个非常常见的示例:

您可以以递归形式调用此函数。在这种情况下,您可能会以空指针或结尾NoneType。在这种情况下,您会收到此错误。因此,在访问该参数的属性之前,请检查它是否不是NoneType

g.d.d.c. is right, but adding a very frequent example:

You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it’s not NoneType.


回答 7

建立估算器(sklearn)时,如果忘记在fit函数中返回self,则会得到相同的错误。

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError:’NoneType’对象没有属性’transform’?

添加return self到拟合功能可修复该错误。

When building a estimator (sklearn), if you forget to return self in the fit function, you get the same error.

class ImputeLags(BaseEstimator, TransformerMixin):
    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        """ do something """

    def transfrom(self, x):
        return x

AttributeError: ‘NoneType’ object has no attribute ‘transform’?

Adding return self to the fit function fixes the error.


回答 8

在Flask应用程序中注释掉HTML时,可能会出现此错误。此处qual.date_expiry的值为None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

删除行或修复它:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

You can get this error with you have commented out HTML in a Flask application. Here the value for qual.date_expiry is None:

   <!-- <td>{{ qual.date_expiry.date() }}</td> -->

Delete the line or fix it up:

<td>{% if qual.date_attained != None %} {{ qual.date_attained.date() }} {% endif %} </td>

回答 9

如果我们分配如下所示的内容,则会引发错误,例如“ AttributeError:’NoneType’对象没有属性’show’”

df1=df.withColumn('newAge',df['Age']).show() 

if we assign something like the below, it will throw error as “AttributeError: ‘NoneType’ object has no attribute ‘show'”

df1=df.withColumn('newAge',df['Age']).show()