我在Chapel有一个课程,我想让它控制它自己的打印声明。所以例如
class Noob {
var name: string, experience:int;
// constructor
}
后来,我想做类似
的事情me = new Noob('brian', 0)
writeln(me)
> Hi, my name is Brian and I have 0 years experience
看起来this应该会有所帮助,但我无法使用readThis()
方法。
答案 0 :(得分:3)
您需要writeThis(f)
方法来覆盖对象的默认writeln
行为:
class Noob {
var name: string, experience:int;
proc writeThis(f) {
f.writef('Hi, my name is %s and I have %t years experience',
this.name, this.experience);
}
}
var noob = new Noob('ben', 2);
writeln(noob);
您还可以使用<~>
方法中的readWriteThis(f)
运算符来处理对象的读取和写入:
class Noob {
var name: string, experience:int;
proc readWriteThis(f) {
f <~> 'Hi, my name is %s and I have %t years experience'.format(this.name, this.experience);
}
}