Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Child/Parent classes, Child Class Returning String Twice?

Easy question and probably very obvious to one of you, but Im unsure of why this happends. So here are the three python files Ive made.

Main Char class:

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

Player class:

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

Init:

from Letsago.player import Player


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

This results in:

Billy
Billy

Why is it being returned twice?

like image 966
Paul Duncan Avatar asked Nov 16 '25 10:11

Paul Duncan


1 Answers

I have put your example in a file called 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

and executed the following (python 2.7 on ubuntu 13.04):

python test.py

and got the following in the console

Billy

Try to isolate the example like I did in one single file and execute it (outside of an interactive shell). Also check your modules and check your from character import *. Be sure that you are importing the correct Player class

like image 101
Bruno Penteado Avatar answered Nov 19 '25 01:11

Bruno Penteado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!