问题
给定一个实例,以及一个包含插槽inst
名称的字符串,如何获取插槽上的值?attr
attr
inst
当然,如果attr
是符号而不是字符串,我通常只会使用(slot-value inst attr)
,但似乎我需要包信息才能正确调用intern
(见下文)。
最小的例子
(defpackage :pack1
(:use :common-lisp)
(:export :*inst*))
(in-package :pack1)
(defclass temp-class ()
((temp-slot :initarg :temp-slot)))
(defvar *inst* (make-instance 'temp-class :temp-slot "value"))
(defpackage :pack2
(:use :common-lisp :pack1)
(:import-from :pack1 :temp-class))
(in-package :pack2)
(let ((inst *inst*) ; In the real example, inst gets defined outside my control,
; in yet another package
(attr "temp-slot"))
(format t "Given package name: ~S; " ; prints fine
(slot-value inst (intern (string-upcase attr) :pack1)))
(format t "No package name: ~S; " ; signals an error
(slot-value inst (intern (string-upcase attr)))))
现有技术
背景
我正在py-format
研究 Python 格式的 Common Lisp 端口{}
。为了实现 Python.
运算符 ( getattr
),我需要将点后面的字符串转换为点前面的对象上的一个槽。