如何在为类变量赋值时减少样板代码

有没有什么办法来简化这个代码,因为每次把一个实例名称来访问类变量是烦人的。 我基本上形成了Kotlin的背景,我们用with来访问这个类的属性。

Kotlin例如:

 val notification = Notification() with(notification){ created_at = datetime.datetime.now() recipient_id = recipient //etc } 

notification.py

 class Notification(CustomerBase, Base): __tablename__ = "notification" created_at = Column(DateTime, nullable=True, default=datetime.datetime.now()) recipient_id = Column(Integer, ForeignKey("users.id"), nullable=True) sender_id = Column(Integer, ForeignKey("users.id"), nullable=True) data = Column(JSONB, nullable=True) message = Column(String, nullable=True) type = Column(String, nullable=True) activity_id = Column(Integer, nullable=True) is_read = Column(BOOLEAN, nullable=True, default=False) sender_info = relationship("User", foreign_keys=[sender_id]) recipient_info = relationship("User", foreign_keys=[recipient_id]) entity_id = Column(Integer, nullable=True) entity_name = Column(String, nullable=True) 

保存通知到会话。

  notification = Notification() notification.created_at = datetime.datetime.now() notification.recipient_id = recipient notification.sender_id = activity.created_by notification.message = add_people_msg(user, added_user, activity) notification.type = NotificationTypes.PEOPLE.value notification.customer_id = activity.customer_id notification.entity_id = activity.id notification.customer_id = activity.customer_id notification.activity_id = activity.id notification.data = activity_data self.session.add(notification) 

 class Notification(CustomerBase, Base): __tablename__ = "notification" # Define table columns created_at = Column(DateTime, nullable=True, default=datetime.datetime.now()) recipient_id = Column(Integer, ForeignKey("users.id"), nullable=True) sender_id = Column(Integer, ForeignKey("users.id"), nullable=True) data = Column(JSONB, nullable=True) message = Column(String, nullable=True) type = Column(String, nullable=True) activity_id = Column(Integer, nullable=True) is_read = Column(BOOLEAN, nullable=True, default=False) sender_info = relationship("User", foreign_keys=[sender_id]) recipient_info = relationship("User", foreign_keys=[recipient_id]) entity_id = Column(Integer, nullable=True) entity_name = Column(String, nullable=True) def __init__(*args, **kwargs): # Dynamically set attributes from keyword arguments # This is not very explicit, # and therefore should be properly documented for k, v in kwargs: setattr(self, k, v) # Set kwork arguments notification_args = { 'created_at': datetime.datetime.now(), 'recipient_id': recipient, 'sender_id': activity.created_by, 'message': add_people_msg(user, added_user, activity), 'type': NotificationTypes.PEOPLE.value, 'customer_id': activity.customer_id, 'entity_id': activity.id, 'customer_id': activity.customer_id, 'activity_id': activity.id, 'data': activity_data } # Add the instance to the session self.session.add(Notification(**notification_args)) 

这是更多的代码行,但更少的重复。

文档:

  • SETATTR
  • kwargs