编程语言
首页 > 编程语言> > Python子/父类,子类返回字符串两次?

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

作者:互联网

简单的问题,对你们中的一个人来说可能非常明显,但我不确定为什么会这样.所以这里是我制作的三个python文件.

主要Char类:

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

为什么要两次归还?

解决方法:

我已将您的示例放在名为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之外).还要检查你的模块并检查你的字符导入*.确保导入正确的Player类

标签:python,string,parent-child
来源: https://codeday.me/bug/20190825/1721431.html