Python访问子类中的超类变量

36

我想在子类中访问self.x的值。我该如何访问它?

class ParentClass(object):

    def __init__(self):
        self.x = [1,2,3]

    def test(self):
        print 'Im in parent class'


class ChildClass(ParentClass):

    def test(self):
        super(ChildClass,self).test()
        print "Value of x = ". self.x


x = ChildClass()
x.test()

1
顺便问一下,你能把错误回溯编辑到问题中吗?这将有助于使这个问题对未来的谷歌搜索者更相关,因为目前该问题与超类或子类没有任何关系。 - David Robinson
我认为你最好将标题命名为“从子类访问超类的实例变量”。在Python中,类变量和实例变量是有区别的。 - Diansheng
2个回答

21

你正确访问了父类变量;你的代码因为打印方式而出现错误。你使用了字符串连接符号.,而不是+,并且将一个字符串和一个列表进行了连接。请修改该行:

    print "Value of x = ". self.x

到以下任何一个:

    print "Value of x = " + str(self.x)
    print "Value of x =", self.x
    print "Value of x = %s" % (self.x, )
    print "Value of x = {0}".format(self.x)

11
class Person(object):
    def __init__(self):
        self.name = "{} {}".format("First","Last")

class Employee(Person):
    def introduce(self):
        print("Hi! My name is {}".format(self.name))

e = Employee()
e.introduce()

嗨!我的名字是 First Last


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接