简体   繁体   中英

python django why class method can be used like a variable?

I see this in the UserCreationForm:

def clean_username(self):
    # Since User.username is unique, this check is redundant,
    # but it sets a nicer error message than the ORM. See #13147.
    username = self.cleaned_data["username"]
    try:
        User._default_manager.get(username=username)
    except User.DoesNotExist:
        return username
    raise forms.ValidationError(self.error_messages['duplicate_username'])

This method can be used in this way:

def register_me(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        uname = form.clean_username

See the last line above . The method is without the ()... Why???

This is because python is not strongly typed (so you can assign any kind of object to any variable) and because functions are first class objects: you can assign them to variables like any normal object.

In your example after assigning *form.clean_username* to uname you can use the uname variable like this: uname() and it will do the same as *form.clean_username()* because you assigned to uname the "runnable" that was referenced by *form.clean_username*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM