2013-08-30 70 views
14

我想訪問子類中的self.x的值。我如何訪問它?python訪問子類中的超類變量

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() 
+1

順便說一句,您可以編輯您的錯誤回溯到這個問題?這將有助於使這個問題與未來的Google員工更相關,因爲這是一個問題,對於超級班或兒童班來說沒有任何問題。 –

+0

我認爲你最好提到標題是「從子類中訪問超類的實例變量」。 python中的類變量和實例變量是有區別的。 – Sean

回答

13

您正確訪問了超類變量;你的代碼會給你一個錯誤,因爲你試圖打印它。您使用.作爲字符串連接而不是+,並連接了一個字符串和一個列表。行

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) 
3
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