我是Python的新手,目前我需要__repr__一个SqlAlchemy类.我有一个可以接受Null值的整数列,SqlAlchemy将其转换为None.例如:
class Stats(Base):
__tablename__ = "stats"
description = Column(String(2000))
mystat = Column(Integer, nullable=True)
Run Code Online (Sandbox Code Playgroud)
__repr__当SqlAlchemy返回时,在函数中表示"mystat"字段的正确方法是什么None?
当您打印在Python的对象,__repr__而__str__不是由用户定义的Python转换的对象字符串表示,用尖括号分隔...
<bound method Shell.clear of <Shell object at 0x112f6f350>>
Run Code Online (Sandbox Code Playgroud)
问题是在Web浏览器中呈现包含必须正常呈现的HTML的字符串.浏览器显然被尖括号弄糊涂了.
我很难找到关于这些表示形成方式的任何信息,如果有一个名称甚至可以.
是否有可能改变了Python代表对象作为字符串的方式,对所有没有一个对象__repr__定义的方法,通过重写__repr__了object类?
那么,如果Python通常会返回"<Foo object at 0x112f6f350>",那么什么钩子可以使它返回"{Foo object at {0x112f6f350}}",或者其他任何东西,而不必直接修改Foo其他所有类?
实现__repr__了一类Foo有成员变量x和y,是有办法来自动填充字符串?不起作用的示例:
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(**self.__dict__)
>>> foo = Foo(42, 66)
>>> print(foo)
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
而另一个:
from pprint import pprint
class Foo(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return "Foo({})".format(pprint(self.__dict__))
>>> foo = Foo(42, 66)
>>> print(foo)
{'x': 42, 'y': 66}
Foo(None)
Run Code Online (Sandbox Code Playgroud)
是的我可以将方法定义为
def __repr__(self):
return "Foo({x={}, y={}})".format(self.x, self.x)
Run Code Online (Sandbox Code Playgroud)
但是当有许多成员变量时,这会变得乏味.
我正在使用Python 3.x,我正在尝试从__repr__函数中获取一个f-string报告,但我似乎无法获得以下格式化字符串,以便按照我期望的方式工作.
我经常收到"SyntaxError:解析时意外的EOF"
def __repr__(self):
return f"Player has {'Soft' if self.soft > 0} {self.count}. Cards are {self.cards}."
Run Code Online (Sandbox Code Playgroud)
如果self.soft> 0},则给出错误的部分是{'Soft'.如果不清楚,我试图包含"Soft"IFF self.soft> 0这个词,如果没有,不要在字符串中添加任何单词.
这两种方法有区别吗?
例如,
from datetime import date
today = date(2012, 10, 13)
repr(today)
'datetime.date(2012, 10, 13);
today.__repr__()
'datetime.date(2012, 10, 13)'
Run Code Online (Sandbox Code Playgroud)
他们似乎做了同样的事情,但为什么有人想要在常规报告中使用后者呢?
我试图让我的基于类的装饰器保持repr()原始包装函数的行为(以匹配functools.wraps装饰器在函数上的工作方式).我正在使用python 3.3.
首先我尝试了functools:
import functools
class ClassBasedDecorator():
def __init__(self, fn):
self.fn = fn
functools.update_wrapper(self, fn)
def __call__(self, *args, **kwargs):
self.fn(*args, **kwargs)
@ClassBasedDecorator
def wrapped(text):
pass
Run Code Online (Sandbox Code Playgroud)
但是当我调用repr()装饰函数时,我得到:
>>> repr(wrapped)
'<__main__.ClassBasedDecorator object at 0x2d8860b6850>'
Run Code Online (Sandbox Code Playgroud)
很好,所以我试着自定义__repr__我的装饰器的方法,它应该被调用repr().
再次使用functools:
class ClassBasedDecorator():
def __init__(self, fn):
self.fn = fn
functools.update_wrapper(
self, fn,
assigned=functools.WRAPPER_ASSIGNMENTS + ('__repr__',)
)
def __call__(self, *args, **kwargs):
self.fn(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
不会改变输出,但会发生一些有趣的事情:
>>> repr(wrapped)
'<__main__.ClassBasedDecorator object at 0x2d8860b69d0>'
>>> wrapped.__repr__()
'<function wrapped at 0x2d8860a9710>'
Run Code Online (Sandbox Code Playgroud)
显式设置__repr__ …
这是一段代码,它进入一个无限递归循环,它只包含__repr__函数,似乎在调用自身.但我真的看不到它是怎么称呼它自己的.而且,我甚至无法理解,它是如何被称为:
class MyList(list): #this is storage for MyDict objects
def __init__(self):
super(MyList, self).__init__()
class MyDict(dict):
def __init__(self, mylist):
self.mylist = mylist #mydict remembers mylist, to which it belongs
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def __repr__(self):
return str(self.mylist.index(self)) #!!!this is the crazy repr, going into recursion
def __str__(self):
return str(self.__repr__())
mylist = MyList()
mydict = MyDict(mylist)
mydict.update({1:2})
print str(mylist.index(mydict)) #here we die :(
Run Code Online (Sandbox Code Playgroud)
执行此代码会导致:
Traceback (most recent call last):
File "test_analogue.py", line 20, …Run Code Online (Sandbox Code Playgroud) 该函数numpy.array_repr可用于创建 NumPy 数组的字符串表示。如何将 NumPy 数组的字符串表示转换为 NumPy 数组?
假设字符串表示如下:
array([-0.00470366, 0.00253503, 0.00306358, -0.00354276, 0.00743946,
-0.00313205, 0.00318478, 0.0074185 , -0.00312317, 0.00127158,
0.00249559, 0.00140165, 0.00053142, -0.00685036, 0.01367841,
-0.0024475 , 0.00120164, -0.00665447, 0.00145064, 0.00128595,
-0.00094848, 0.0028348 , -0.01571732, -0.00150459, 0.00502642,
-0.00259262, 0.00222584, 0.00431143, -0.00379282, 0.00630756,
0.001324 , -0.00420992, -0.00808643, 0.00180546, 0.00586163,
0.00177767, -0.0011724 , -0.00270304, 0.00505948, 0.00627092,
-0.00496326, 0.00460142, -0.00177408, -0.00066973, 0.00226059,
0.00501507, -0.00261056, -0.00617777, 0.00269939, -0.01023268,
0.00338639, 0.00483614, 0.00086805, 0.00041314, -0.0099909 ,
0.00356182, -0.00788026, 0.00245763, 0.00371736, 0.00343493,
-0.00037843, -0.0013632 , -0.00210518, …Run Code Online (Sandbox Code Playgroud) 我正在创建一个简单的数组包装类,并希望它的__toString()方法被格式化为Python列表,例如:["foo", "bar", 6, 21.00002351].将每个元素转换为字符串是不够的,因为字符串对象实际上在列表表示中被引用.
repr()PHP中是否有等价物,如果没有,PHP实现会是什么样子?
好的,我想使用 repr() 打印出一堆列表和嵌套数组的文本版本。
但我希望数字只有 4 个小数位,而不是:42.7635745114 而是 32.7635。
我想使用 repr() 因为它处理嵌套数组的能力很好。编写我自己的打印循环是一个没有吸引力的选择。
当然有某种方法可以重载 repr 来做到这一点吗?我看到有一个 repr 和 reprlib 模块,但例子真的很少,就像不存在一样。