Python脚本以不同的顺序执行

2024-04-20 10:36:13 发布

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

为了简单起见,我在这里只发布了两个模块(其他模块中有“pass”)start.py模块一直工作,直到我在player.py模块中更改了一些内容,在类CreateNewPlayer中,现在发生的是:

我从命令行开始使用start.py,但它没有首先显示我的简介(splashscreen函数),而是直接跳到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 = []

Tags: namepyimportselfgametruenewage
1条回答
网友
1楼 · 发布于 2024-04-20 10:36:13

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实例

您还应该从Player中删除maleinventory类属性

相关问题 更多 >