29

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

2 回答 2

20

您正确访问了超类变量;由于您尝试打​​印它的方式,您的代码会给您一个错误。您用于.字符串连接而不是+, 并连接一个字符串和一个列表。换行

    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)
于 2013-08-30T15:50:43.453 回答
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()

Hi! My name is First Last

于 2013-08-30T16:06:33.213 回答