Python子类/父类,子类返回字符串两次?

2024-03-29 00:04:00 发布

您现在位置:Python中文网/ 问答频道 /正文

简单的问题,可能对你们中的一个来说很明显,但我不确定为什么会这样。下面是我制作的三个python文件。

主字符类:

class Character():
    """
    This is the main parents class for creation of
    characters, be they player, NPC or monsters they
    shall all share common traits
    """

    def __init__(self, name, health, defense):
        """Constructor for Character"""
        self.name = name
        self.health = health
        self.defense = defense

玩家等级:

from character import *

class Player(Character):
    """
    The player class is where heros are made
    They inherit common traits from the Character class
    """

    def __init__(self, name, health, defense, str, int):
        Character.__init__(self, name, health, defense)
        self.str = str
        self.int = int

初始化:

from Letsago.player import Player


hero = Player("Billy", 200, 10, 10, 2)    
print hero.name

这将导致:

Billy
Billy

为什么要退货两次?


Tags: thenamefromselfinitisclassint
1条回答
网友
1楼 · 发布于 2024-03-29 00:04:00

我将您的示例放在一个名为test.py的文件中:

class Character():
    """
    This is the main parents class for creation of
    characters, be they player, NPC or monsters they
    shall all share common traits
    """

    def __init__(self, name, health, defense):
        """Constructor for Character"""
        self.name = name
        self.health = health
        self.defense = defense


class Player(Character):
    """
    The player class is where heros are made
    They inherit common traits from the Character class
    """

    def __init__(self, name, health, defense, str, int):
        Character.__init__(self, name, health, defense)
        self.str = str
        self.int = int


hero = Player("Billy", 200, 10, 10, 2)
print hero.name

并执行了以下操作(ubuntu 13.04上的python 2.7):

python test.py

控制台里有下面的

Billy

尝试像我在一个文件中所做的那样隔离这个示例并执行它(在一个交互式shell之外)。还要检查模块并检查from character import *。确保导入的是正确的Player

相关问题 更多 >