Skip to main content
 首页 » 编程设计

python之在 Python 中打印继承的类

2025年05月04日8dflying

我正在尝试将两个类(class)合并为一个类(class)。在代码块的末尾,您将看到一个名为 starwarsbox 的类。这合并了字符和框类。目标是打印出一个由星号和星球大战角色信息组成的盒子(这是我学习的)。我曾尝试查找如何使用 repr 但没有成功实现它。我感谢您的帮助。

我得到 <__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)) 

请您参考如下方法:

首先,正如 chepner 提到的,最后一行应该是 print(str(newbox))。

starwarsbox 实现了 __str__,但 box 和 character 没有。

盒子应该是这样的:

    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。 :)