我只看过__repr__在类定义中设置方法的示例.是否__repr__可以在定义中或定义后更改for函数?
我试图没有成功......
>>> def f():
pass
>>> f
<function f at 0x1026730c8>
>>> f.__repr__ = lambda: '<New repr>'
>>> f
<function __main__.f>
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用OOP python,我不确定__repr__函数继承.由于父类函数看起来像这样:
def __repr__(self):
'''Returns representation of the object'''
return("{}({!r})".format("Class name", self._param))
Run Code Online (Sandbox Code Playgroud)
我想知道是否更好地使用通用方法(也适用于子类),如下所示:
def __repr__(self):
'''Returns representation of the object'''
return("{}({!r})".format(self.__class__.__name__, self._param))
Run Code Online (Sandbox Code Playgroud)
或者如果在每个班级中覆盖该功能是一个好习惯.
另外,请忽略编码部分,因为我将它留在后面.
如果我有一个字符串(0x61 0x62 0xD),repr该字符串的函数将返回'ab\r'.
有没有办法进行反向操作:如果我有字符串'ab\r'(带字符0x61 0x62 0x5C 0x72),我需要获取字符串0x61 0x62 0xD.
所以我在python中遇到了一些非常奇怪的东西.我尝试将列表的引用添加到自身.代码可能有助于证明我所说的比我能表达的更好.我正在使用IDLE编辑器(交互模式).
>>>l=[1,2,3]
>>>l.append(l)
>>>print(l)
[1,2,3,[...]]
>>>del l[:-1]
>>>print(l)
[[...]]
Run Code Online (Sandbox Code Playgroud)
到目前为止,输出是预期的.但是当我这样做的时候.
y=l[:]
print(y)
Run Code Online (Sandbox Code Playgroud)
对我而言,似乎输出应该是
[[...]]
Run Code Online (Sandbox Code Playgroud)
但它是
[[[...]]]
Run Code Online (Sandbox Code Playgroud)
显然,它不是创建列表的副本,而是在y中引用列表.
y [0]是l返回True.我似乎无法找到一个很好的解释.有任何想法吗?
以下代码抛出RuntimeError: maximum recursion depth exceeded while getting the str of an object.我可以用两种不同的方式解决无限递归,但我不明白为什么每种修复都有效,因此不知道使用哪种,或者两种方法是否正确.
class FileError( Exception ):
def __init__( self, filename=None, *a, **k ):
#Fix 1: remove super
super( FileError, self ).__init__( self, *a, **k )
self.filename = filename
def __repr__( self ):
return "<{0} ({1})>".format( self.__class__.__name__, self.filename )
#Fix 2: explicitly define __str__
#__str__ = __repr__
print( FileError( "abc" ) )
Run Code Online (Sandbox Code Playgroud)
如果我删除super,代码运行但不打印任何东西.这没有意义,因为根据这篇文章,Python中的__str__和__repr__之间的区别,省略__str__将调用,__repr__但这似乎不会发生在这里.
相反,如果我继续调用super并添加__str__ = __repr__,那么我得到预期的输出并且没有递归.
有人可以解释为什么无限递归存在,为什么每次更改都会解决inifinte递归,以及为什么一个修复可能比另一个更优先?
似乎__repr__函数可以返回不同的方式.
我有一个InfoObj类,它存储了很多东西,其中一些我并不特别希望自己设置类的用户.我意识到没有什么蟒蛇是受保护的,他们可能只是潜水,并设置也无妨,但似乎在定义它__init__使得它更可能有人会看到它,并假设它是罚款,只是传递进去.
(示例:当确定对象已完全填充时由验证函数设置的布尔值,以及存储足够信息时从其他值计算的值...例如A = B + C,所以一次设置A和B,然后计算C并将对象标记为Valid = True.)
那么,考虑到所有这些,哪个是设计__ repr__输出的最佳方法?
bob = InfoObj(Name="Bob")
# Populate bob.
# Output type A:
bob.__repr__()
'<InfoObj object at 0x1b91ca42>'
# Output type B:
bob.__repr__()
'InfoObj(Name="Bob",Pants=True,A=7,B=5,C=2,Valid=True)'
# Output type C:
bob.__repr__()
'InfoObj.NewInfoObj(Name="Bob",Pants=True,A=7,B=5,C=2,Valid=True)'
Run Code Online (Sandbox Code Playgroud)
...类型C的要点是不愉快地将我在C++中设置为"私有"的所有东西作为构造函数的参数,并让使用该类的队友使用接口函数设置它,即使它更多的工作对他们来说 在这种情况下,我将定义一个不带某些东西的构造函数,以及一个稍微难以注意到的单独函数,用于__repr__
如果它有所不同,我打算使用它们的__repr__输出将这些python对象存储在数据库中并使用它们进行检索eval(),至少除非我想出更好的方法.队友手动创建完整对象而不是通过正确的接口函数的结果只是一种类型的信息检索可能不稳定,直到有人弄清楚他做了什么.
我__repr__()在对象上调用函数x如下:
val = x.__repr__()
然后我想将val字符串存储到SQLite数据库.问题是val应该是unicode.
我试过这个没有成功:
val = x.__repr__().encode("utf-8")
和
val = unicode(x.__repr__())
你知道怎么纠正这个吗?
我正在使用 Python 2.7.2
我观察到一种类型
help
Run Code Online (Sandbox Code Playgroud)
在Python repl中,有人得到
Type help() for interactive help, ...
Run Code Online (Sandbox Code Playgroud)
当一种类型
help()
Run Code Online (Sandbox Code Playgroud)
一个人被踢进了帮助模式.我很确定这是因为site._Helper定义__repr__()(对于第一个示例)和__call__() (对于第二个示例).
我喜欢这种行为(只提示对象和可调用语法),我想对我通过SWIG导出到Python的C++类做同样的事情.这是我尝试做的一个简单例子
helpMimic.h
-----------
class HelpMimic
{
public:
HelpMimic() {};
~HelpMimic() {};
char *__repr__();
void operator()(const char *func=NULL);
};
helpMimic.cxx
-------------
char *HelpMimic::__repr__()
{
return "Online help facilities are not yet implemented.";
}
void HelpMimic::operator()(const char *func)
{
log4cxx::LoggerPtr transcriptPtr = oap::getTranscript();
std::string commentMsg("# Online help facilities are not yet implemented. Cannot look up ");
if (func) {
commentMsg += …Run Code Online (Sandbox Code Playgroud) 我知道在 Python Shell 中,当您键入时,>>> object它会显示该object.__repr__方法,如果您键入,>>> print(object)它也会显示该object.__str__方法。
但我的问题是,有没有一种__repr__在执行Python文件时进行打印的简短方法?
我的意思是,在 file.py 中,如果我使用print(object)它,它会显示object.__str__,如果我只是键入,object它不会显示任何内容。
我尝试过使用print(object.__repr__)但它打印<bound method object.__repr__ of reprReturnValue>
或者这是不可能的?
概括
我有dataclass10多个字段。print()使用它们将有趣的上下文埋藏在默认值的墙中 - 让我们通过不再不必要地重复这些来使它们变得更友好。
Python 中的数据类
Python 的@dataclasses.dataclass()( PEP 557 ) 提供自动可打印表示 ( __repr__())。
假设这个例子,基于 python.org 的:
from dataclasses import dataclass
@dataclass
class InventoryItem:
name: str
unit_price: float = 1.00
quantity_on_hand: int = 0
Run Code Online (Sandbox Code Playgroud)
装饰器@dataclass(repr=True)(默认)将得到print()一个很好的输出:
InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
Run Code Online (Sandbox Code Playgroud)
我想要的:跳过打印默认值
repr它会打印所有字段,包括您不想显示的隐含默认值。
print(InventoryItem("Apple"))
# Outputs: InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
# I want: InventoryItem(name='Apple')
Run Code Online (Sandbox Code Playgroud)
print(InventoryItem("Apple", unit_price="1.05"))
# Outputs: InventoryItem(name='Apple', unit_price='1.05', quantity_on_hand=0)
# I want: InventoryItem(name='Apple', unit_price='1.05') …Run Code Online (Sandbox Code Playgroud)