简体   繁体   中英

How to access class variable in Python?

I'm new to Python programming and wondering how can I access to variables I have declared in one file to another? I'm working on Django and have two files:

  1. forms.py

     class ContactForm(forms.Form): full_name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(max_length=1000) 
  2. views.py

     from .forms import ContactForm def contact(request): e = ContactForm() toPrint = e.get(email) print(toPrint) 

I'm just testing it to print on terminal to help me learn how to access those variables to use them in views.py

in the views you would normally pass in the data that went into the form then you can grab it with cleaned_data like this

def contact(request):
    context = {}
    if request.method == 'POST':
        form = ContactForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email', '')
            # do something with email here??
    else:
        form = ContactForm()
    context['form'] = form
    return render(request, 'signup.html', context)

EDIT: As was pointed out in the comments, this answer does not work in the specific case of django, because of some django-magic. But in general this should be correct.

First of, you should declare the variables in the __init__ function (the constructor) of the ContactForm class. Then you store it under self :

class ContactForm(forms.Form):
    def __init__(self):
        super().__init__()
        self.full_name = forms.CharField(max_length=100)
        self.email = forms.EmailField()
        self.message = forms.CharField(max_length=1000)

In either case (if you keep the code like you have it, or you use the constructor function explicitly), you access the variables simply as

e = ContactForm()
to_print = e.email
....
e = ContactForm()

如果您的表格经过验证,则可以通过

e.cleaned_data.get('email')

Django forms use a so-called metaclass. What this does in this specific case is capture all Field instance defined on the form, and put them in a dictionary called declared_fields . You can see the source code here . You would access the original field as ContactForm.declared_fields['email'] .

The form makes a copy of declared_fields and puts it in the fields attribute to allow changes to fields in a single form instance. You would then access the fields as follows:

e = ContactForm()
e.fields['email']

As said by others, if it weren't for the metaclass, you would just use ContactForm.email or e.email .

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