在 python 对象中,重写对象的方法__repr__
和方法__str__
可以分别提供对象的“明确”和“人类可读”表示。如何在 Racket 中实现类似的行为?
我在这里遇到了printable<%>
界面,看起来它应该可以用于此目的,但我无法让它像我期望的那样工作。基于文档中的标准“鱼”示例:
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
这是我得到的输出:
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
所以问题是三方面的:
为什么它会以这种方式运行,即在对象的明显单一渲染上调用多个方法?
custom-print、custom-write 和 custom-display 方法的计算结果是什么?他们应该只是简单地返回一个字符串,还是应该根据具体情况实际产生打印、写入或显示的副作用?例如,custom-write 方法是否应该在内部调用该
write
函数?这是用于此目的的正确构造吗?如果没有,有没有/它是什么?