Python类声明自动根据变量名设置名称。

huangapple go评论65阅读模式
英文:

Python class declarative auto set name based on variable name

问题

我受到了Django / SQLAlchemy和Peewee ORM的启发,但我永远无法理解在声明性类中如何将字段的名称作为类调用的名称。

示例:

from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

基本上,CharField 类在初始化时会自动设置name='first_name'属性。

有人能帮我理解吗?

英文:

I have been inspired by the Django / SQLalchemy and Peewee ORMs but I can never understand how in a declarative class it managed to take the name of the field as the name of the class called.

Example:

from django.db import models
    
class Musician (models.Model):
     first_name = models.CharField (max_length = 50)
     last_name = models.CharField (max_length = 50)
     instrument = models.CharField (max_length = 100)

Basically, the CharField class will automatically set the name='first_name' attribute during initialization

Can someone help me understand?

答案1

得分: 0

Python中的元类。您有一个类构造函数,该函数查看类的所有属性,然后执行操作(例如分配名称属性等)。

首先,我查找了一个看起来不错的内容,但搜索元类或声明性基类,您将找到更多信息。在我看来,这对于一个Stack Overflow回答来说信息太多了。

https://realpython.com/python-metaclasses/

英文:

Python metaclasses. You have a class construction function which looks at all the attributes of the class and then does things (like assigns a name attribute, etc).

First thing I googled that looked good, but search for metaclass or declarative base-class and you'll find more information. It's too much info for a SO answer, in my opinion.

https://realpython.com/python-metaclasses/

huangapple
  • 本文由 发表于 2020年1月7日 02:12:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定