Python脚本以我想要的不同顺序执行

时间:2014-03-16 16:36:57

标签: python python-2.7 module

为简单起见,我只在这里发布了两个模块(其他模块有&#34;传递&#34;在其中)。 start.py 模块一直工作,直到我在 player.py 模块中更改了某些内容 CreateNewPlayer ,现在会发生什么:< / p>

我从命令行开始使用 start.py ,但不是首先显示我的简介( splashcreen 函数),而是直接跳转到 CreateNewPlayer 马上。

我做错了什么?

这是第一个文件 start.py

import sys
import custom_error
import player
import handler
import prompt
import game


def splash_screen():
    print chr(27) + "[2J"
    print "*" * 80
    print "***** Welcome to ZOMBIE ADVENTURE *****"
    print "*" * 80
    print "\nSelect option:"
    print "1. Start a new game"
    print "2. Load existing game"
    print "3. Quit"

    while True:
        action = prompt.menu()

        if action == 1:
            create_player = player.CreateNewPlayer()
            new_player = player.Player(create_player.name, create_player.age, create_player.male, create_player.inventory)

            print "\nYour name is %s and you're %d old." % (new_player.name, new_player.age)
            print "It is %s that you're a man." % new_player.male

            print "\n1. Continue to game"
            print "2. Back to main menu"
            action = prompt.menu()

            while True:
                if action == 1:
                    game.Engine.launchgame()
                elif action == 2:
                     exit(1)
                else:
                    custom_error.error(1)
                    # a_game = game.Engine('Room1')
                    # a_game.LaunchGame(new_player)
        elif action == 2:
             handler.load()
        elif action == 3:
             exit(1)
        else:
             custom_error.errortype(0)

splash_screen()

现在名为 player.py 的第二个文件:

import sys
import custom_error
import prompt
import game

class Player(object):


     male = True
     inventory = []

     def __init__(self,name,age,male,inventory):
        self.name = name
        self.age = age
        self.male = male
        self.inventory = inventory

 class CreateNewPlayer(object):


     print chr(27) + "[2J"
     print "-" * 80
     print "Character creation"
     print "-" * 80

     name = raw_input("Type your character name > ")
     age = int(raw_input("Put down your age in numbers > "))
     male = True
     sex = raw_input("Are you a male or female? M/F > ")

     if sex.lower() == "m":
         male = True
     elif sex.lower() == "f":
         male = False
     else:
         print "Please type either 'M' or 'F'"
         pass

     inventory = []

1 个答案:

答案 0 :(得分:1)

CreatePlayerCharacter中的属性是类属性;该类定义中的所有代码在创建类时运行,即在导入文件时运行,而不是在创建类实例时运行。

到目前为止,查看您的代码,您可能更好地定义类方法Player.create

class Player(object):

    ...

    @classmethod
    def create(cls):
        name = raw_input("Type your character name > ")
        ...
        return cls(name, age, male, [])

可以访问:

new_player = Player.create()

并将直接返回Player个实例。

您还应该从male删除inventoryPlayer类属性。