python - 在某些 lisp 语言上,这个 Python 散列写入/访问代码的等效项是什么?

标签 python data-structures clojure lisp scheme

<分区>

这段 Python 代码的等价物是什么:

class Player:
    def __init__(self): 
        self.hp = 10
        self.pos = [0,0,0]
        self.items = []
    def damage(self,dmg):
        self.hp -= dmg

player = Player()
player.damage(3)
player.pos[0] += 5
player.items.append("banana")

print player.hp, player.pos, player.items
>> 3 [5,0,0] ["banana"]

在 Clojure(或其他 Lisp)中?

最佳答案

在普通 Lisp 中:

(defclass player ()
  ((hp :accessor hp :initform 10)
   (pos :accessor pos :initform (list 0 0 0))
   (items :accessor items :initform nil)))

(defmethod damage ((a-player player) damage)
  (decf (hp a-player) damage))

在 REPL 中

; compiling (DEFCLASS PLAYER ...)
; compiling (DEFMETHOD DAMAGE ...)
CL-USER> (defparameter *player* (make-instance 'player))

*PLAYER*
CL-USER> (damage *player* 3)
7
CL-USER> (incf (car (pos *player*)) 5)
5
CL-USER> (push :banana (items *player*))
(:BANANA)
CL-USER> (list (hp *player*) (pos *player*) (items *player*))
(7 (5 0 0) (:BANANA))
CL-USER> 

就我个人而言,我会将 pos 分成单独的 xyz,并且可能定义一些将东西放入和取出库存的方法,以防万一我决定稍后更改表示。

关于python - 在某些 lisp 语言上,这个 Python 散列写入/访问代码的等效项是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216594/

相关文章:

java - 在 Clojure 中将十六进制摘要转换为长整数

Python 输出换行

通过 numpy 数组进行复杂数学计算累积和的 Pythonic 方法

python - 将带有索引的 numpy 数组转换为 pandas 数据框

python - 尝试连接套接字时出现错误 10051

algorithm - 给定 n-1*n 数组,找到缺失的数字

scala - 是否有像 Clojurescript 这样的 Scala?又名集成 Scala 单页应用程序

java - 链表删除 : why don't we override the head with previous?

data-structures - 如何在函数式编程中实现内存有效的集合的无损操作?

clojure - 尝试在 Clojure 中拆分字符串遇到惰性序列问题