2016-02-11 55 views
2

我試圖將兩個類合併成一個類。在代碼塊的末尾,您會看到一個名爲starwarsbox的類。這包含字符和框類。目標是打印出一個由星號和星球大戰角色的信息組成的盒子(這是爲了我的學習)。我試圖查找如何使用repr,但沒有實施它的運氣。我感謝您的幫助。在Python中打印繼承類

我得到<__main__.starwarsbox object at 0x000000000352A128>

class character: 
    'common base class for all star wars characters' 
    charCount = 0 

    def __init__(self, name, occupation, affiliation, species): 
     self.name = name 
     self.occupation = occupation 
     self.affiliation = affiliation 
     self.species = species 
     character.charCount +=1 

    def displayCount(self): 
     print ("Total characters: %d" % character.charCount) 

    def displayCharacter(self): 
     print ('Name :', self.name, ', Occupation:', self.occupation, ', Affiliation:', self.affiliation, ', Species:', self.species) 


darth_vader = character('Darth Vader', 'Sith Lord', 'Sith', 'Human') 
chewbacca = character('Chewbacca', 'Co-pilot and first mate on Millenium Falcon', 'Galactic Republic & Rebel Alliance', 'Wookiee') 


class box: 
    """let's print a box bro""" 

    def __init__(self, x, y, title): 
     self.x = x 
     self.y = y 
     self.title = title 

    def createbox(self): 
     for i in range(self.x): 
      for j in range(self.y): 
       print('*' if i in [0, self.x-1] or j in [0, self.y-1] else ' ', end='') 
      print() 

vaderbox = box(10, 10, 'box') 
vaderbox.createbox() 


class starwarsbox(character, box): 
    def __init__(self, name, occupation, affiliation, species, x, y, title): 
     character.__init__(self, name, occupation, affiliation, species) 
     box.__init__(self, x, y, title) 

    def __str__(self): 
     return box.__str__(self) + character.__str__(self) 

newbox = starwarsbox('luke','jedi','republic','human',10,10,'box') 

print(repr(newbox)) 
+1

'repr'調用'__repr__',而不是'__str__'。 – chepner

+0

那會是什麼?我嘗試了'print(str(newbox))',它仍然顯示'__ main __。starwarsbox object 0x000000000350A128' – stuffatwork190

+0

在'box'和'Character'類中實現'__str__'函數,然後使用print(newbox)。 – Zety

回答

1

首先,chepner提到,最後一行應該是print(str(newbox))

starwarsbox已執行__str__,但框和字符不。

框應類似於:

def __str__(self): 
     result = "" 
     for i in range(self.x): 
      for j in range(self.y): 
       result += '*' if i in [0, self.x - 1] or j in [0, self.y - 1] else ' ' 
      result += '\n' 
     return result 

和性格應該是這樣的:

def __str__(self): 
     return 'Name :' + self.name + ', Occupation:' + self.occupation + ', Affiliation:' + self.affiliation + ', Species:' + self.species 

比較這對你的代碼,看看你能如何使用__str__的實現都實現了displayCharacter和createBox。 :)

+0

非常感謝你!這工作! :-)。我很感激。我一直試圖在我的頭上繞了兩天......大聲笑。 – stuffatwork190

+0

'print(str(newbox))'和'print(newbox)'有什麼區別? – Zety

+1

我只是試着做'print(newbox)',它和print(str(newbox))一樣。我猜測,因爲其他更改確保它是一個正在打印的字符串。 – stuffatwork190