Python-Child 类触发父类

标签 python python-2.7

我需要在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/

相关文章:

python - Jenkins : how to print the contents of a text file to the build log?

Python Unicode 十六进制字符串解码

python2和pandas : get all occurrence of day during a year in a dataframe

python-2.7 - flask 登录可重复使用的 cookies

python - 如何在 Django URL 模式中使用小数?

python - 提高Python中 `compute_optimal_weights`函数的性能

python - 在Python中循环遍历文件目录

python - UTF8编码的字符串'Jalape\xc3\xb1o'('Jalapeño')是否包含8或9个字符?

python - 如何在 Mac 上指定路径

Pythonic 方式 : Utility functions in class or module