在python中,如果我在对象上调用方法,则将对象本身的引用放入函数中。我想在dart中有类似的行为,但是我找不到如何使用self
变量获得与python中相同的行为。
我基本上想实现这样的行为:
class Parent:
def __init__(self):
self.child = Child(self)
class Child:
def __init__(self, parent):
self.parent = parent
在dart中,我希望它看起来像这样:
class Parent {
final Child child;
Parent() : this.child = Child(this);
}
class Child {
final Parent parent;
Child(parent) : this.parent = parent;
}
但是将this关键字放在dart的括号中会导致错误。
错误消息是:
Error compiling to JavaScript:
main.dart:4:33:
Error: Can't access 'this' in a field initializer.
Parent() : this.child = Child(this);
^^^^
Error: Compilation failed.
如何实现dart python代码中演示的行为?
最佳答案
您既不能在构造函数头中也不可以在初始化器列表中访问this
(了解有关here的更多信息)。
如果要执行此操作,则必须在构造函数主体中初始化child
变量:
class Parent {
Parent() {
child = Child(this);
}
Child child; // Cannot be final.
}
关于python - 如何在构造函数中使用 `this`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59847898/