python访问子类中的超类变量

时间:2013-08-30 15:49:04

标签: python

我想在子类中访问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()

2 个答案:

答案 0 :(得分:14)

您正确访问了超类变量;您的代码会因为您尝试打印它而导致错误。您使用.进行字符串连接而不是+,并将字符串和列表连接起来。改变行

    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)

答案 1 :(得分:7)

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()

Hi! My name is First Last