我想访问子类中 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()
最佳答案
您正确访问了父类(super class)变量;由于您尝试打印它的方式,您的代码会给您一个错误。您使用 .
代替 +
进行字符串连接,并连接了一个字符串和一个列表。换行
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)
关于python访问子类中的父类(super class)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536929/