对象方法可以返回该对象的实例吗? [英] Can an object method return an instance of the object?

查看:33
本文介绍了对象方法可以返回该对象的实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们团队中的某人在我们的Person模型上写了一个方法(User的扩展",尽管它不是从User继承的):

Someone on my team wrote a method on our Person Model (an 'extension' of User, although it does not inherit from User):

class Person(models.Model):
    @staticmethod
    def from_user(user):
        try:
            return Person.objects.get(username=user.username)
        except ObjectDoesNotExist:
            return None

因此,从理论上讲, Person.from_user(request.user)应该返回正确的Person.相反,我得到 AttributeError:'NoneType'对象没有属性'objects'.

So theoretically, Person.from_user(request.user) should return the correct Person. Instead I'm getting AttributeError: 'NoneType' object has no attribute 'objects'.

我是静态方法的新手,所以我可能会缺少一些东西-但在我看来这是不可能的.这很容易用其他方式解决.我只是想知道是否有一种真正的方法可以让Person方法返回像这样的Person实例,以及我是否应该修复此方法或抛弃它.

I'm new to staticmethods, so I might be missing something--but it seems to me that this is impossible. It was easy to solve in other ways; I'm just wondering if there's any real way to have a method of Person return an instance of Person like this, and if I should repair this method or just ditch it.

如果我跳入PDB并导入模型,则 Person.objects.get(username = user.username)会按预期工作.无法看到将Person设置为None的方式或位置.

If I jump into PDB and import the model, Person.objects.get(username=user.username) works as expected. Can't see how or where Person is getting set to None.

推荐答案

所显示的代码不应引发错误:完全有效.

The code you've shown shouldn't throw an error: it's perfectly valid.

但是,更好的方法是使用类方法而不是静态方法.类方法的要点是它会自动传递给类本身,您可以在方法中使用它:

However a better way to do this would be to use a classmethod instead of a staticmethod. The point of a classmethod is that it is automatically passed the class itself, which you can use in the method:

@classmethod
def from_user(cls, user):
    return cls.objects.get(username=user.username)

这篇关于对象方法可以返回该对象的实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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