我想在子类中访问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()
Run Code Online (Sandbox Code Playgroud)
Dav*_*son 15
您正确访问了超类变量; 您的代码会因为您尝试打印它而导致错误.您用于.字符串连接而不是+,并连接字符串和列表.改变线
print "Value of x = ". self.x
Run Code Online (Sandbox Code Playgroud)
以下任何一项:
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)
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
Hi! My name is First Last
| 归档时间: |
|
| 查看次数: |
45252 次 |
| 最近记录: |