Python __repr__和无 [英] Python __repr__ and None
问题描述
我是Python的新手,目前我需要为SqlAlchemy类添加__repr__
.
我有一个可以接受Null
值的整数列,而SqlAlchemy将其转换为None
.
例如:
I'm quite new to Python and currently I need to have a __repr__
for a SqlAlchemy class.
I have an integer column that can accept Null
value and SqlAlchemy converts it to None
.
For example:
class Stats(Base):
__tablename__ = "stats"
description = Column(String(2000))
mystat = Column(Integer, nullable=True)
当SqlAlchemy返回None
时,在__repr__
函数中表示"mystat"字段的正确方法是什么?
What is the correct way to represent the "mystat" field in the __repr__
function when SqlAlchemy returns None
?
推荐答案
__repr__
应该返回描述对象的字符串.如果可能的话,它应该是一个有效的Python表达式,其结果等于一个相等的对象.对于诸如int
或str
的内置类型,这是正确的:
The __repr__
should return a string that describes the object. If possible, it should be a valid Python expression that evaluates to an equal object. This is true for built-in types like int
or str
:
>>> x = 'foo'
>>> eval(repr(x)) == x
True
如果这不可能,则应为唯一描述对象的'<...>'
字符串.默认的__repr__
是此示例:
If that's not possible, it should be a '<...>'
string uniquely describing the object. The default __repr__
is an example of this:
>>> class Foo(object):
pass
>>>
>>> repr(Foo())
'<__main__.Foo object at 0x02A74E50>'
它使用内存中对象的地址唯一标识它.当然,地址不会告诉我们有关对象的太多信息,因此重写__repr__
并返回描述对象状态的字符串很有用.
It uses the object's address in memory to uniquely identify it. Of course address doesn't tell us much about the object so it's useful to override __repr__
and return a string describing the object's state.
对象的状态由它包含的其他对象定义,因此在您的对象中包含它们的repr
是有意义的.这正是list
或dict
的作用:
The object's state is defined by other objects it contains so it makes sense to include their repr
in yours. This is exactly what list
or dict
do:
>>> repr(['bar', Foo()])
"['bar', <__main__.Foo object at 0x02A74710>]"
在您的情况下,状态位于您的Column
属性中,因此您想使用它们的repr
.您可以为此使用%r
格式,它会插入参数的repr()
:
In your case, the state is in your Column
properties so you want to use their repr
. You can use the %r
formatting for this, it inserts a repr()
of the argument:
def __repr__(self):
return '<Stats: description=%r, mystat=%r>' % (self.description, self.mystat)
使用新格式的等效项:
def __repr__(self):
return '<Stats: description={0.description!r}, mystat={0.mystat!r}>'.format(self)
这篇关于Python __repr__和无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!