“自我”从何而来? Django中的属性得到它的实例?

时间:2015-07-02 09:40:41

标签: python django instance self

我试图抓住Django和Python的工作。我总是对函数中self参数的含义感到困惑。

示例:

class RegistrationForm(forms.ModelForm):
    email = forms.EmailField(label='Your Email')
    password1 = forms.CharField(label='Password', \
                    widget=forms.PasswordInput())
    password2 = forms.CharField(label='Password Confirmation', \
                    widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ['username', 'email']

    def clean_password2(self):
        print "Inside clean_password2:"
        print self
        print "_________________________________________________"
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match")
        return password2

终端输出为:

[02/Jul/2015 15:03:26]"GET /accounts/register/ HTTP/1.1" 200 5118
Inside clean_password2:
<tr><th><label for="id_username">Username:</label></th><td><input id="id_username" maxlength="30" name="username" type="text" value="TestUser" /><br /><span class="helptext">Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.</span></td></tr>
<tr><th><label for="id_email">Your Email:</label></th><td><input id="id_email" name="email" type="email" value="test@test.com" /></td></tr>
<tr><th><label for="id_password1">Password:</label></th><td><input id="id_password1" name="password1" type="password" /></td></tr>
<tr><th><label for="id_password2">Password Confirmation:</label></th><td><input id="id_password2" name="password2" type="password" /></td></tr>

也就是说,self属性是上面显示的内容。问题是,这个函数和self属性从何而来?

我没有询问self作为python的语言特性的作用。我的问题是关于self如何在Django中获取实例。

此代码属于here的存储库。

TL; DR:为什么在我打印自己时打印所有HTML。它来自哪里?

1 个答案:

答案 0 :(得分:1)

如评论中所述,当您打印self时,您正在打印ModelForm实例。

在Python中打印对象时,它会调用对象的__str__方法。

如果查看Form类的__str__方法,它会调用as_table方法,该方法将字段显示为html表的内容。这是你看到的输出。

def __str__(self):
    return self.as_table()