hy - hy 语言中有没有办法在 self 上使用 doto ?

标签 hy

希望有人能帮我解决这个问题。我正在将一些 python 代码移植到 hy,并试图弄清楚如何使用 doto 宏删除一些重复的代码。例如,看看这样的 python 类:

class Foo(object):
  def __init__(self, x, y, z):
      self.x = x
      self.y = y
      self.z = z

如何在 hy 中将其转换为使用 doto?

(defclass Foo [object]
  [[__init__ (fn [self x y z]
               (doto self  ;
                 (setv ...) ; What goes here? 
  ))]])

问题是你通常会做这样的事情:

(defclass Foo [object]
  [[__init__ (fn [self x y z]
               (setv self.x x)
               (setv self.y y)
               (setv self.z z))]])

我没有看到在 self 上使用 (doto) 的方法。

最佳答案

这是一个有趣的想法。你可以这样做:

(doto self
  (setattr "x" x)
  (setattr "y" y)
  (setattr "z" z))

但情况也好不了多少。考虑定义一个宏:

(defmacro vars-to-attrs [obj &rest attrs]
  (let [[actions (list (map
                        (fn (a) `(setattr (str '~a) ~a))
                        attrs))]]
    `(doto ~obj ~@actions)))

然后这样调用它:

(vars-to-attrs self x y z)

这作为一个函数可能会更好:

(defun vars-to-attrs-fun [obj &rest attrs]
  (for [a attrs]
    (setattr obj a (get (locals) a))))

然后这样调用它:

(vars-to-attrs-fun self 'x 'y 'z)

或者等效的:

(vars-to-attrs-fun self "x" "y" "z")

关于hy - hy 语言中有没有办法在 self 上使用 doto ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28949486/

相关文章:

海浪 : Howto simplest for loop in hy?

python - 在 Hy 中指定元类的语法

python3/hy - 评估 python 中的 hy 表达式?

hy - if 和 cond 有什么区别?

python - 在 Hy 中使用 numpy.nditer

destructuring - Hylang 映射解构

python - 用 Hy 中的索引替换列表/字典元素

emacs - 在 Emacs 中为 Hy 使用 repl

json - 如何将 hylang s-表达式序列化为 PostgreSQL json/json-b?

python - conda 托管环境中的 Shebang