python访问子类中的父类(super class)变量

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

最佳答案

您正确访问了父类(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/

相关文章:

python - Scapy 中的 prn 参数

python - 根据 async def 实现协程

python - 迭代Python字典中元组键的一部分

python - 从数据框中删除未出现一定次数的用户名?

python - 由于某种原因无法从 p 标签获取文本 - Selenium (Python)

python - 如何通过 onchange 方法在不同模型上创建记录?

python - 在Python中编写一个保存和返回值的函数

python - 在 Keras 中,为什么必须根据神经网络的输出来计算损失函数?

python - Gensim 库 Python 3.4 : http://www. lfd.uci.edu/~gohlke/pythonlibs/的安装问题

Python:嵌套列表合并并在同一索引中添加 int