编程语言
首页 > 编程语言> > Python类方法抛出AttributeError

Python类方法抛出AttributeError

作者:互联网

我在让类方法在Flask中运行时遇到问题.

在models / User.py中:

from mongoengine import *

class User(Document):
  first_name = StringField()
  last_name = StringField()
  ...

  def __init__(self, arg1, arg2, ...):
    self.first_name = arg1
    self.last_name = arg2
    ...

  @classmethod
  def create(self, arg1, arg2, ...):
    #do some things like salting and hashing passwords...
    user = self(arg1, arg2, ...)
    user.save()
    return user

在主应用程序python文件中:

from models import User
...
def func():
  ...

  #Throws "AttributeError: type object 'User' has no attribute 'create'"
  user = User.create(arg1, arg2, ...) 

如果不实例化User对象,是否可以在User类上调用create?我使用的是Python 2.7.2,我还尝试了使用create = classmethod(create)的非修饰符语法,但这没有用.提前致谢!

编辑:我发现一个问题:models文件夹不包含__init__.py文件,因此它不是一个模块,因此从models import用户实际上并没有导入我想要的文件.它没有给我以前的错误,因为我以前在与应用程序python脚本相同的目录中有一个models.py模块,但是删除它之后,我从未删除过相应的.pyc文件.现在,我收到错误AttributeError:’module’对象没有属性’create’而不是我以前拥有的属性,但是我确定它现在正在导入正确的文件.

EDIT2:解决.然后,我将导入更改为from models.User import User,现在点击了方法.

解决方法:

问题是双重的:

> User.py文件位于models /文件夹中,这意味着我的导入实际上是在models.py文件中寻找User类,该类不再存在,但仍被无误导入,因为models.pyc文件仍然存在周围
>导入不正确,无法在目录中导入.它应该是来自models.User import User,只要models /文件夹是一个模块,那么我要做的就是触摸models / __ init__.py.

标签:attributeerror,exception,flask,class-method,python
来源: https://codeday.me/bug/20191101/1980249.html