我寫的屬性變化的歷史sqlalchemy
模型。屬性列表對於歷史很重要,我保留在類屬性history_attributes中。爲什麼sqlalchemy.Column實例的屬性'name'消失?
from sqlalchemy import Integer, Column, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class HistoryAttribute:
def __init__(self, descriptor, display_name, use_message=False):
self.name = descriptor.name
self.display_name = display_name
self.use_message = use_message
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
first_name = Column(String(100))
email = Column(String(100))
history_attributes = (
HistoryAttribute(descriptor=first_name, display_name='User name'),
email
)
print(User.history_attributes[0].name)
>>> None
print(User.history_attributes[1].name)
>>> email
爲什麼Column
實例的屬性"name"
消失,如果我通過一個其他類的構造函數?當然,我可以寫first_name = Column('first_name', String(100)
和代碼將正常工作, 但我不希望添加Column.name
明確。我使用namedtuple,然後我傳遞給HistoryAttribute
類的構造避免了問題,但它是非常相似的柺杖。
declared_attr不適合,因爲我想從類中獲取history_attributes,但這引發了使用classmethod的想法,該方法返回所需的元組HistoryAttribute實例 – Stright
我很困惑declare_attr是如何得到的。配置完成後,我確信訪問該類會爲您提供實例。也就是說,在課堂建設過程中,我相當肯定元類將用正確的東西替換declared_attr。在你的情況下,classmethod會起作用,但除非你記憶,否則會稍微短一些。 –
也許我誤解了你,但declared_attr給了我相同的結果( [代碼示例](https://codeshare.io/5RB0dB) – Stright