作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个例子来自一本 Scala 书籍:
trait IO { self =>
def run: Unit
def ++(io: IO): IO = new IO {
def run = { self.run; io.run }
}
}
object IO {
def empty: IO = new IO { def run = () }
}
书中给出的解释如下:
self 参数让我们可以将此对象称为 self 而不是 this。
这句话意味着什么?
最佳答案
self
只是声明它的对象中 this
的别名,它可以是任何有效的标识符(但不是 this
>,否则不会创建别名)。因此,self
可用于从内部对象内部的外部对象引用 this
,否则 this
的含义会有所不同。也许这个例子会让事情变得清晰:
trait Outer { self =>
val a = 1
def thisA = this.a // this refers to an instance of Outer
def selfA = self.a // self is just an alias for this (instance of Outer)
object Inner {
val a = 2
def thisA = this.a // this refers to an instance of Inner (this object)
def selfA = self.a // self is still an alias for this (instance of Outer)
}
}
object Outer extends Outer
Outer.a // 1
Outer.thisA // 1
Outer.selfA // 1
Outer.Inner.a // 2
Outer.Inner.thisA // 2
Outer.Inner.selfA // 1 *** From `Outer`
关于scala - Scala 中的自论证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30108539/
这个问题已经有答案了: What is the purpose of the `self` parameter? Why is it needed? (26 个回答) 已关闭 9 年前。 我已经用 J
R 中 ~. 参数的含义是什么? 例如plot(~.,xyz..) 我已经看到这个论点在各种情况下多次使用,并且由于很难在谷歌上有意义地搜索符号,所以我几乎没有取得成功。 最佳答案 这是一个公式,采用
我是 Python 的新手。我不明白如何/为什么使用 self 参数: class Person: def __init__(self, name): self.name =
我是一名优秀的程序员,十分优秀!