【发布时间】:2019-01-03 16:26:03
【问题描述】:
我想干净整洁地显示/打印我的 sqlalchemy 课程。
在Is there a way to auto generate a __str__() implementation in python?
中,答案You can iterate instance attributes using vars, dir, ...:... 在简单类的情况下会有所帮助。
当我尝试将它应用到 Sqlalchemy 类(如来自
Introductory Tutorial of Python’s SQLAlchemy 的类 - 见下文)时,我得到 - 除了成员变量之外,还有以下条目作为成员变量:
_sa_instance_state=<sqlalchemy.orm.state.InstanceState object at 0x000000004CEBCC0>
如何避免此条目出现在__str__ 表示中?
为了完整起见,我也将链接的stackoverflow问题的解决方案放在下面。
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
如前所述,这是Is there a way to auto generate a __str__() implementation in python?的解决方案:
def auto_str(cls):
def __str__(self):
return '%s(%s)' % (
type(self).__name__,
', '.join('%s=%s' % item for item in vars(self).items())
)
cls.__str__ = __str__
return cls
@auto_str
class Foo(object):
def __init__(self, value_1, value_2):
self.attribute_1 = value_1
self.attribute_2 = value_2
应用:
>>> str(Foo('bar', 'ping'))
'Foo(attribute_2=ping, attribute_1=bar)'
【问题讨论】:
标签: python sqlalchemy boilerplate