是否有 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
值得注意的是,apply
和 update
在 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)
这样的语法foreach
和 map
可以说 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__
//在大多数情况下,函数参数实现相同的目的
关于python - 相当于 python __getattr__/__setattr__ 的 scala,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10658920/