【问题标题】:In Python, how does one override the behavior of a class instance typed on a line by itself在 Python 中,如何覆盖单独在一行上键入的类实例的行为
【发布时间】:2017-01-12 18:02:28
【问题描述】:

如果没有打印(我相信它会调用 str()),当变量单独位于一行时会发生什么。

这有点做作,我知道,但我在测试我正在创建的课程时在 Jupyter 笔记本中遇到了这个问题,现在我很好奇。我似乎无法找到正确的 Google 搜索字词集以在文档中找到答案。

我就这样定义了一个类:

class ExceptionList(BaseException):
    pass
    # I've implemented, in very standard ways, the following methods
        # __str__()
        # __getitem__()
        # __delitem__()
        # __repr__()
    # I doubt any other specifics of the class are pertinent

编辑

这是 repr() 实现:

def __repr__(self):
    return "{}({})".format(self.__class__.__name__, repr(self.__exception_list))

附:我根据http://brennerm.github.io/posts/python-str-vs-repr.html对该方法进行了编码

编辑

我的 repr() 实现导致了这种行为:

e = ExceptionList(["Oh, no"])


e

“异常列表(['哦,不'])”

所以考虑一下:

e1 = Exception("Oh no!")
e2 = ExceptionList("Oh no!")

在单独的笔记本单元格中:

e1

异常('哦,不!')

e2

__main__.ExceptionList()

顺便说一下(也许?)输出:

e2.__class__

接近了:

__main__.ExceptionList

它只是与定义类的范围有关吗?是内置函数的一些特殊行为吗?

这种行为是调用某些我不知道的方法的结果吗?我尝试实现使用dir() 生成的所有方法,尽管我敢打赌这并不详尽。

这可能对我的实现无关紧要,但现在我需要知道!

样板仇恨威慑:

  • 我什么都不知道。
  • 我是一个糟糕的程序员。
  • “我以为蟒蛇是蛇……”
  • 我几乎没有资格使用烤面包机。
  • 请原谅这篇文章对 SO 磁盘空间的可悲使用。

【问题讨论】:

  • 无法复制。 ExceptionList 产生与 Python 2 和 3 中的 Exception 相同的输出。
  • 大概你已经定义了__repr__ 来输出"__main__.ExceptionList()",因为这就是执行此操作的方法。
  • 嗯,不完全是。看看我上面的编辑。 __repr__() 打印出实例的字符串表示,以便 eval() 可以用来重新创建它。
  • 没有。 __repr__ 在您自己键入实例时负责产生输出的方法。显然,当你这样做时,你会得到你描述的输出,因为 这就是你定义 __repr__ 要做的事情
  • 这不是真的。我在 /__repr__() 的输出中也有类的参数。该类包含一个列表,该列表的 repr 在 ExceptionList 的括号内。另外,我的 repr 实现没有 /__main__ 前置。

标签: python class jupyter


【解决方案1】:

如果一行的唯一内容是变量或对象,则评估该行并返回变量或对象,而不是将其存储到变量中。

a = 5 + 2  # 5+2 is evaluated and stored in a
5 + 2 # 5+2 is evaluated
a # a is evaluated

class SomeCustomClass:
    def __init__(self, *args):
        pass

scc = SomeCustomClass()
scc # returns a reference to this instance, but ref is not stored

Jupyter、IPython、IDLE 等许多 python 接口都会显示该行的评估。

>>> 5+2
7
>>> a=5+2
[Nothing]
>>> a
7
>>> scc
<__main__.SomeCustomClass instance at 0x7fb6d5943d40>

&lt;__main__.SomeCustomClass instance at 0x7fb6d5943d40&gt; 被称为类的表示。如果您查看Python's Data Model,您将看到此表示是由对象的__repr__ 方法指定的。

修改SomeCustomClass

class SomeCustomClass:
    def __init__(self, *args):
        pass
    def __repr__(self):
        return "SomeCustomClass repr"

>>> scc = SomeCustomClass()
>>> scc
SomeCustomClass repr
>>> s = str(scc) #implicit call to __repr__
>>> s
SomeCustomClass repr

现在添加__str__方法:

class SomeCustomClass:
    def __init__(self, *args):
        pass
    def __repr__(self):
        return "SomeCustomClass repr"
    def __str__(self):
        return "SomeCustomClass str"

>>> scc = SomeCustomClass()
>>> scc
SomeCustomClass repr
>>> s = str(scc) #explicit call to __str__
>>> s
SomeCustomClass str

【讨论】:

  • 感谢您的回答。它是用来“评估”我所追求的类实例的方法。
猜你喜欢
  • 2023-02-09
  • 2012-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 2012-09-27
  • 2020-10-14
  • 1970-01-01
相关资源
最近更新 更多