为什么我需要在此类中导入类,而不是在文件的顶部? [英] Why do I need to import a class within this class, instead of at the top of the file?

查看:125
本文介绍了为什么我需要在此类中导入类,而不是在文件的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,昨天我发布了一个我遇到的类方法的问题(对象方法可以返回对象的实例吗?),答案是如果您喜欢,可以将其更改为类方法,但是没有你的代码不应该按原样工作的原因。把它改成一个班的方法,所以我继续前进我的生活。现在我有另一个问题,下面的方法(同一个类)不起作用,告诉我'NoneType'对象没有属性'对象'。我跳入调试器,手动输入完全相同的代码工作正常。我将 import User 行从文件顶部移动到函数本身,现在它可以工作。这是使用User类的文件中唯一的地方。个人和用户没有与外键关系链接 - 他们只是共享一个用户名,我们以这种方式进行查找。



我还应该补充说,这两种方法一直工作到几天前,在我们的承诺历史上我没有找到任何改变。

 类人(models.Model):

def to_user(self):
'''返回用户链接到Person或None(需要第三个
派对包)'''
try:
from django.contrib.auth.models import User
return User.objects.get(username = str(self.username))
除了ObjectDoesNotExist:
print(没有使用用户名{0}找到关联用户format(self.username))
return none


解决方案

因为我有一个循环导入。 / p>

So, yesterday I posted a problem with a class method I was having (Can an object method return an instance of the object?) and the answer was "You can change it to a class method if you like, but there's no reason your code shouldn't work as it is." Changing it to a class method worked, so I moved on with my life. Now I'm having another problem where the below method (same class) didn't work, telling me that 'NoneType' object has no attribute 'objects'. I jumped into the debugger, and the exact same code worked fine when entered manually. I moved the import User line from the top of the file into the function itself, and now it works. This is the only place in the file where the User class is used. Person and User are not linked with a foreign key relationship--they just share a username and we do the lookup that way.

I should also add that both of these methods worked fine up until a few days ago, and I haven't been able to find any alterations of them in our commit history.

Class Person(models.Model):

    def to_user(self):
        '''returns user linked to Person or None(needed for some third
            party packages)'''
        try:
            from django.contrib.auth.models import User
            return User.objects.get(username=str(self.username))
        except ObjectDoesNotExist:
            print("No associated user found using username {0}".format(self.username))
            return None

解决方案

Because I had a circular import.

这篇关于为什么我需要在此类中导入类,而不是在文件的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆