将全局变换为类

时间:2016-11-16 19:16:38

标签: python python-3.x

我一直在使用python的一个小文本游戏的全局变量,并且已经遇到很多文章说全局变量在python中是不可能的。我一直在努力了解如何获得下面的内容(只是一个健康变量,能够更改它并打印它),使用类工作,但我很困惑如何在类中转换类似的东西。任何帮助,例如,指向正确的方向都会很棒。

以下是我使用变量的示例。

import sys
import time

health = 100
b = 1

def intro():
    print("You will die after two moves")


def exittro():
    time.sleep(1)
    print("Thanks for playing!")
    sys.exit()


def move():
    global health
    global b
    health -= 50

    if health <= 51 and b >0:
        print("almost dead")
        b = b - 1


def death():
    if health == 0 or health <= 0:
        print("...")
        time.sleep(1)
        print("You died\n")
        time.sleep(2)
        print("Dont worry, this game sucks anyway\n")
        exittro()

intro()

a = 1

while a == 1:
    input("Press Enter to move")
    move()
    death()

谢谢

编辑:这是我一直试图做的事情......

class Test:
def __init__(self):
    number = 100

def __call__(self):
    return number

def reduceNum(self):
    number -=10

def printNum(self):
    print(number)

a = 1
while a == 1:
    input("Enter")
    Test.self.reduceNum()
    Test.self.printNum()

1 个答案:

答案 0 :(得分:3)

我会避免使用类,因为类通常较慢。您可以使函数返回health变量的新值。

我还建议制作一个主控制器函数来获取返回值并将其应用于其他函数。这可以防止函数范围之外的全局变量。

import time

def intro():
    print("You will die after two moves")


def outro():
    time.sleep(1)
    print("Thanks for playing!")
    # sys.exit() # You can avoid this now by just stopping the program normally


def move(health):
    health -= 50

    if health <= 51:
        print("almost dead")
    return health  # Return the new health to be stored in a variable


def death(health):
    if health <= 0:
        print("...")
        time.sleep(1)
        print("You died\n")
        time.sleep(2)
        print("Dont worry, this game sucks anyway\n")
        return True  # Died
    return False  # Didn't die

def main():
    health = 100  # You start with 100 health
    intro()
    while not death(health):
        # While the death function doesn't return `True` (i.e., you didn't die) ...
        input("Press enter to move")
        health = move(health)  # `health` is the new health value
    outro()

如果要使用类,则需要通过instance = Test()实际实例化类(从中创建新对象)。您还需要将变量存储为self的属性(所以self.number = number),因为任何局部变量都彼此不同。

class Test:
    def __init__(self):
        self.number = 100

    def __call__(self):
        return self.number

    def reduceNum(self):
        self.number -= 10

    def printNum(self):
        print(self.number)

a = 1
game = Test()
while a == 1:
    input("Enter")
    game.reduceNum()
    game.printNum()
    # Or:
    print(game())
    # As you've changed `__call__` to return the number as well.