简体   繁体   中英

class definition inside a class?

class ItemForm(djangoforms.ModelForm):
    class Meta:
        model = Item
        exclude = ['added_by']

i can not understand what this piece of code is doing .i understood that ItemForm is inheriting Modelform but then a class definition inside a class ??

The Item class is :

class Item(db.Model):
    name = db.StringProperty()
    quantity = db.IntegerProperty(default=1)
    target_price = db.FloatProperty()
    priority = db.StringProperty(default='Medium',choices=[
      'High', 'Medium', 'Low'])
    entry_time = db.DateTimeProperty(auto_now_add=True)
    added_by = db.UserProperty()

It's part of Django's magic. The metaclass for ModelForm (among other classes) looks for an inner Meta class and uses it to make various changes to the outer class. It's one of the deeper parts of Python that most people will never have to deal with first-hand.

In Python you can define classes within other classes as a way of encapsulating the inner class. The way Django is using this is actually quite excellent.

See this link for more info: http://www.geekinterview.com/question_details/64739

Meta is a special class definition.

In this example, it is a simple inheritance model. ModelForm creates a form based on a Model class, so via giving a class definiton to ModelForm class, it creates the form elements according to related Model class definiton.

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