如何从python中的子对象访问基类属性

时间:2017-11-13 01:46:12

标签: python

我习惯用C ++编写,我遇到了属性错误。基本上我有一个通过子类访问的父属性并使用子类对象。

class temp ():
    def __init__(self):
        self.t1 = 500
        self.t2 ="temp testing"

class parent ():
    def __init__(self):
        self.a1 = ""
        self.a2 = 0
        self.alist = []

class child (parent):
    def __init__(self):
        parent.__init__(self)
        ## i want to define is C++ , initalizing values
        a1 = "fun1"
        a2 = 200
        t1 = temp()
        t1.t1 = 100
        t1.t2 = "modified testing"
        alist.append(t1)

    def dis_name(self):
        print a1

gchild = child()
gchild.a1 = "modified child"
gchild.dis_name()

1 个答案:

答案 0 :(得分:0)

您的子对象中缺少多个self引用。

class temp ():
    def __init__(self):
        self.t1 = 500
        self.t2 ="temp testing"

class parent ():
    def __init__(self):
        self.a1 = ""
        self.a2 = 0
        self.alist = []

class child (parent):
    def __init__(self):
        parent.__init__(self)
        self.a1 = "fun1"
        self.a2 = 200
        t1 = temp()
        t1.t1 = 100
        t1.t2 = "modified testing"
        self.alist.append(t1)

    def dis_name(self):
        print(self.a1)

gchild = child()
gchild.a1 = "modified child"
gchild.dis_name()