python访问子类中的超类变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18536929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:58:48  来源:igfitidea点击:

python accessing super class variable in child class

python

提问by user1050619

I would like to access the value of self.x in the child class. How do I access it?

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

回答by David Robinson

You accessed the super class variable correctly; your code gives you an error because of how you tried to print it. You used .for string concatenation instead of +, and concatenated a string and a list. Change the line

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

    print "Value of x = ". self.x

to any of the following:

以下任何一项:

    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)

回答by GLES

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

Hi! My name is First Last