在 Python 类之间传递变量

在 Python 中,可以通过多种方式在类之间传递变量。这些方法可以根据需要的场景来选择,常见的方式包括构造函数传参、类属性、方法调用、全局变量、以及使用单例模式。以下是一些常用的方式及其示例:

在这里插入图片描述

1、问题背景

在 Python 中,需要在两个不同的类之间传递变量。在下面的示例中,想要在 InterrogationRoom 类中设置一个 elf_rescued 变量,并在 Armory 类中使用它。如果 elf_rescued 为 True,则用户可以打开武器柜;否则,武器柜应该保持原样。

2、解决方案

为了在两个类之间传递变量,可以使用以下步骤:

  1. 在 InterrogationRoom 类中,定义一个名为 elf_rescued 的变量,并将其初始化为 False。
  2. 在 InterrogationRoom 类中,创建一个 situation_change() 函数,用于更新 elf_rescued 变量。
  3. 在 Armory 类中,调用 InterrogationRoom 类中的 situation_change() 函数,以获取 elf_rescued 的最新值。
  4. 在 Armory 类中,根据 elf_rescued 的值决定是否允许用户打开武器柜。

下面是修改后的代码:

class InterrogationRoom(Scene):

    def __init__(self):
        self.elf_rescued = False

    def enter(self):
        print("Coming out of the prison area you find yourself on a long, narrow corridor with doors on each side.")
        print("Passing one of the doors you see your comrade tied up to a strappado.")
        print("He is clearly in a lot of pain and by the looks of his body this isn't the first torture device " \
            "he was experimented with.")
        print("Taking him with you could be risky as he isn't in the shape to move on his own.")
        print("However, he is your comrade ever since you fought together in the 'War of the Seven Armies'.")
        print("Will you ease his pain and make sure he won't be tortured by the orcs anymore or will you take him " \
            "with you?")

        action = raw_input("> ")

        if "leave him" in action:
            print("As hard it is, you decide to leave him behind. You grab a dagger from the table and " \
            "push it right in his chest. You leave the room.")
            return 'armory'

        elif "rescue him" in action:
            print("You cut him down from the rope. He tells you that all your gear has been taken to the Armory. " \
            "However, one of the guards has the key to open the weapon locker.")
            print("You decide to go to the Guards' Quarters.")
            self.elf_rescued = True
            return 'guards_quarters'

        else:
            print("You can't do that.")
            return 'inter_room'


class Armory(Scene):

    def enter(self):
        print("You enter the armory, where you see a weapons locker and 3 orcs in the back of the room.")
        print("What do you do?")

        action = raw_input("> ")

        while True:

            if "attack" in action and not elf_rescued:
                print("You can't attack them without a weapon.")
                return 'armory'

            elif "leave" in action:
                print("You leave and keep going ahead on the main corridor.")
                return 'main_hall'

            elif "open locker" in action and elf_rescued:
                print("You open the weapons locker, where you get a nice weapon and shield.")
                locker_opened = True

            elif "attack" in action and locker_opened:
                print("You attack the orc pack from behind. Cutting down two heads right away.")
                print("The third one jumps away and looks angry as hell.")
                print("Prepare for battle.")

            else:
                print("You can't do that.")
                return 'armory'

现在,当用户选择在 InterrogationRoom 类中营救精灵时,elf_rescued 变量将被设置为 True。当用户进入 Armory 类时,elf_rescued 的值将被传递过来,并用于决定是否允许用户打开武器柜。

根据需要的不同,你可以在 Python 类之间传递变量的多种方式中选择最合适的。例如,构造函数传参和方法调用是最常见和推荐的方式,它们保持了代码的清晰性和可维护性。全局变量和单例模式则适用于需要在多个地方共享同一份数据的场景,但使用时需谨慎。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值