2
問題
給定一個instance,inst
和含有slot的名稱的字符串attr
,我怎樣才能獲得時隙attr
上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)))))
現有技術
- 從this question,我想通了,我的問題是,
intern
被創建在不同的包比在其定義的類中的一個符號。 - 似乎從this question,我不能簡單地從實例中提取的包信息,所以我必須找出另一種方式(除了使用
intern
到那裏)
背景
我正在研究py-format
一個Common Lisp端口 Python的{}
-formatting。要實現Python .
運算符(getattr
),我需要將點後面的 字符串轉換爲點之前的對象上的插槽。
謝謝 - 最後一點自省將幫助我重新思考語法 – Felipe 2014-10-07 21:26:21