python - 相当于 python __getattr__/__setattr__ 的 scala

标签 python scala dynamic properties getter-setter

是否有 scala 等效于 python __getattr__/__setattr__(以及其他 __*__ 方法?)。一些内置的东西或者一些特征?

最佳答案

对于 __getattr____setattr__您必须等到有更多见识的人描述新的 Scala 2.10 反射 API。 (当然:它永远不会直接翻译。这完全取决于您的用例。如果您只想要一个动态类,那么将来会有一个 Dynamic 特征;如果您只想要一点点那么,围绕模式匹配进行设计可能是一个显而易见的选择。)

至于众多other __*__ methods in Python :

全局事物

  • __call__apply()//行为几乎相同
  • __metaclass__//依赖于用例:
    • 当前 class继承或trait混入可能有用
    • 在许多情况下,元类所做的只是实例构造,这避免了对 super() 的调用。 ;在 Scala 中 super()总是在构造函数中调用。
  • __repr__ , __str__toString()
  • __eq__equals()
  • __init__//在类主体中隐式调用
  • __new__//不直接存在;取决于用例 early initialisation
  • __del__//缺少
  • __nonzero__//不是真的,除了 implicit def toBool[MyType](a: MyType): Boolean = ...

容器类型

  • __len__length , size或者容器中的任何约定
  • __getitem__apply(i: IndexType)//容器是 Scala 中的函数
  • __setitem__update(i: IndexType, v: ValueType)
  • __delitem__//不需要特殊处理;容器公约
  • __iter__foreach(block: ValueType => Unit)//返回值:map , flatMap

值得注意的是,applyupdate在 Scala 中特殊,就像它们的 Python 对应物一样。它们允许使用以下语法:

val x = collection(elem) // val x = collection.apply(elem)
collection(elem) = y // collection.update(elem, y)

类似地,就像 Python 的 __iter__允许像 (el for el in container) 这样的语法foreachmap可以说 for (el <- container) yield el .

运算符

通常不需要特殊处理,因为我们可以直接定义它们:

  • __add__ , __sub__ , …//只定义 def + (arg: T)def - (arg: T)

这也包括比较运算符

  • __lt__ , __ge__def <(other: T) , def <=(other: T)

然而,就像在 Python 中一样,编译器中有一些针对高级事物的特殊情况:

  • __radd__ , __rsub__ , …//右结合运算符;约def +: (arg: T)def -: (arg: T) (附加 : )
  • __iadd__ , __isub__ , …//修改运算符:def += (arg: T) , ……

上下文管理器

  • __enter__ , __exit__//在大多数情况下,函数参数实现相同的目的

另请参阅:List of Scala's "magic" functions

关于python - 相当于 python __getattr__/__setattr__ 的 scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658920/

相关文章:

python - 数据框过滤列列表中的空值

来自 Scala 解释器的 Scaladoc

jquery - IE9 没有将 css 应用到使用 jQuery.after 动态创建的元素

c++ - 使用 python 编写 C++ 脚本

python - 如何根据单个scrapy.Spider的不同命令设置不同的IP?

python - IRC 机器人使循环休眠而不中断主循环

Scala 依赖类型无法编译

json - 玩2 Json格式,捕获Int或String

c++ - 将信息读入结构数组 C++

c - 动态结构数组