gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:47:19 25 4
gpt4 key购买 nike

这个问题很简单,对你们中的一个人来说可能很明显,但我不确定为什么会这样。所以这是我制作的三个 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

为什么会被返回两次?

最佳答案

我已将您的示例放在名为 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

关于Python 子/父类,子类返回字符串两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17015883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com