相关疑难解决方法(0)

如何在普通类中使用等效于 __post_init__ 的方法?

我想存储在我的代码中使用的实体并避免多次出现。因此,我的想法是使用一种__init__方法来收集我的类的主要数据,然后使用一种__post_init__方法从我的类对象中计算 id。这是代码:

class Worker(Base):
    __tablename__='worker'
    id = Column(Integer,primary_key=True)
    profile=Column(String(100),nullable=False)
    useragent=Column(String(100),nullable=False)
    def __init__(self,useragent,profile):
        """ specify the main information"""
        print('init')
        self.profile= profile
        self.useragent=useragent
    def __post_init__(self):
        """ compute an id based on self, the worker"""
        self.id=id(self)
        print('dans post init')
Run Code Online (Sandbox Code Playgroud)

在此示例中,__init__可以使用该方法,但它不会__post_init__像我们对 dataclass 所期望的那样运行该方法,例如。

如何在执行该方法后立即运行此__init__方法?

python sqlalchemy

7
推荐指数
2
解决办法
6580
查看次数

标签 统计

python ×1

sqlalchemy ×1