我需要在Python中从子对象修改父对象上声明的对象。我知道在java中可以通过在初始化子对象时将父对象作为参数传递来修改子对象的父对象。我不需要继承从父级到子级的所有内容,我只需要子级显示和隐藏父级上声明的框架。例如在 Java 中。
public class Parent(){
public Child1 objtchild1;
public Parent(){ ]
Child2 panel = new Child2(this);
Child1 objtchild1 = new Child1();
}
public class Child1 (){
public int var = 1;
}
public class Child2 () {
private Parent parent;
public Child(Parent parent) {
this.parent = parent;
parent.objtchild1.var=2;//Modify parent child object
}
我想应用 Model View Controller ,其中 View 与 Controller 交互。就像下面的 url 一样,但是是在 python 中。
MVC codeprojects.com example
上面关于 Java 的示例可以用 Python 实现吗?
最佳答案
Python 中的 Java 代码等效于:
class Parent(object):
def __init__(self):
# make sure to make objtchild1 first, as panel will try and alter it
self.objtchild1 = Child1()
self.panel = Child2(self)
class Child1(object):
def __init__(self):
self.var = 1
class Child2(object):
def __init__(self, parent):
self.parent = parent
# modify parent child object
self.parent.objtchild1.var = 2
关于Python-Child 类触发父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49301732/