V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-10-09 12:32:34 +08:00 · 2642 次点击
    这是一个创建于 1998 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from .models import Comment

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

    比如以上代码
    4 条回复    2018-10-09 13:51:28 +08:00
    baskershu
        1
    baskershu  
       2018-10-09 13:38:43 +08:00
    cosven
        2
    cosven  
       2018-10-09 13:40:03 +08:00
    这里的 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  
       2018-10-09 13:42:09 +08:00 via Android
    我的错
    jmc891205
        4
    jmc891205  
       2018-10-09 13:51:28 +08:00
    一般使用内部类是为了更好的封装 把内部类的 scope 限制在外部类内部

    针对 Django 的 ModelForm 来说 Quora 上有关于"class Meta"的讨论,你可以参考一下: https://www.quora.com/Why-do-we-use-the-class-Meta-inside-the-ModelForm-in-Django
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4064 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 05:17 · PVG 13:17 · LAX 22:17 · JFK 01:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.