推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
luckjs2017
V2EX  ›  Python

class 里有 class 目的是啥?

  •  
  •   luckjs2017 · Oct 9, 2018 · 3953 views
    This topic created in 2907 days ago, the information mentioned may be changed or developed.
    from .models import Comment

    class CommentForm(forms.ModelForm):
    class Meta:
    model = Comment
    fields = ('name', 'email', 'body')

    比如以上代码
    4 replies  •  2018-10-09 13:51:28 +08:00
    baskershu
        1
    baskershu  
       Oct 9, 2018
    cosven
        2
    cosven  
       Oct 9, 2018
    这里的 Meta class 主要是有一个作用:避免污染 CommentForm 的属性名字空间。这个设计可能是出自 django。
    在 peewee 的文档中也有说道 [这个]( http://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata)。

    补充一下它的原理:forms.ModelForm 这个类应该是有自己的元类 (metaclass),元类里面有黑魔法。

    比如你可能会写这样一段代码:
    ```
    form = CommentForm(xxx)
    print(form.name)
    ```
    如上这个例子,form 对象为什么会有 name 属性呢?这就是它的元类的黑魔法

    所以在这个例子中,LZ 问 “ class 的 class 有什么用” ,感觉有点没有问道点子上。

    ------------------

    不过,我们平常其实也有可能把一个 class 写在一个 class 里面,这就非常简单,类似于私有变量,不希望别的模块引用这个 class。
    Sanko
        3
    Sanko  
       Oct 9, 2018 via Android
    我的错
    jmc891205
        4
    jmc891205  
       Oct 9, 2018
    一般使用内部类是为了更好的封装 把内部类的 scope 限制在外部类内部

    针对 Django 的 ModelForm 来说 Quora 上有关于"class Meta"的讨论,你可以参考一下: https://www.quora.com/Why-do-we-use-the-class-Meta-inside-the-ModelForm-in-Django
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2520 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:45 · PVG 09:45 · LAX 18:45 · JFK 21:45
    ♥ Do have faith in what you're doing.