我想要解決Django和Python的問題。我一直對功能中的self
參數感到困惑。Django中的'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="[email protected]" /></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
作爲Python的語言功能的作用。我的問題是如何self
在Django中獲取實例。
該代碼的一部分的存儲庫是here。
TL; DR:爲什麼打印自己的HTML時會打印所有內容?那來自哪裏?
http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self-in-python的重複 – TheGeorgeous
我聽到有人說「明確優於隱式」 –
@ The Gentle:這個問題不是你展示的內容的重複。我並沒有問自己作爲Python的語言特性的作用。我的問題正是關於如何在Django中獲得實例。在一個非常敏銳的案例中,我提到了這個例子。 如果您仍然覺得它是重複的,請給出一個簡短的答案。問題關閉。 – user248884