gpt4 book ai didi

oop - python 的 __repr__ 和 __str__ 的 Racket 等价物?

转载 作者:行者123 更新时间:2023-12-04 01:44:10 25 4
gpt4 key购买 nike

在 python 对象中,覆盖方法 __repr____str__一个对象的定义允许人们分别提供该对象的“明确的”和“人类可读的”表示。如何在 Racket 中实现类似的行为?

我遇到了 printable<%>界面 here ,看起来它应该可用于此目的,但我无法让它像我期望的那样工作。基于文档中的标准“鱼”示例:

(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!"
>

所以这个问题有三个方面:

  1. 为什么它会以这种方式运行,即在对象的明显单一渲染上调用多个方法?

  2. custom-print、custom-write 和 custom-display 方法的计算结果应该是什么?他们应该简单地返回一个字符串,还是应该实际承担打印、写入或显示的副作用(视情况而定)?例如。自定义写入方法是否应调用 write内部功能?

  3. 这是用于此目的的正确结构吗?如果没有,有没有/它是什么?

最佳答案

至于

  1. Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?

你不小心在write中使用了print,所以写入值时,会先打印值。

(define/public (custom-write port)
(print "Write called!"))

display 中也存在类似的问题。

还要记住打印/写入/显示到正确的端口。

尝试

#lang racket
(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 (~a "Print " current-size "\n") port))
(define/public (custom-write port)
(write (~a "Write " current-size "\n") port))
(define/public (custom-display port)
(display (~a "Display " current-size "\n") port))))

在repl中你会看到:

> (define f (new fish% [size 10]))
> f
"Print 10\n"
> (display f)
Display 10
> (write f)
"Write 10\n"

关于oop - python 的 __repr__ 和 __str__ 的 Racket 等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com