英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论