我试图抓住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。它来自哪里?