如何在变量中更改变量?

2024-09-28 21:05:32 发布

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

这是我的密码:

hp1 = 100
health1 = 'you have', hp1

hp1 = hp1 - 50
health1

print hp1
print health1

这是它打印的内容:

50
('you have', 100)

为什么hp1在健康体内没有改变?你知道吗


Tags: you密码内容haveprinthp1health1
3条回答

以下行:

health1 = 'you have', hp1

正在创建具有两个值的tuple"you have"100(请注意,hp1的值是复制的,而不是引用的)。然后将这个tuple赋值给一个名为health1的新变量。你知道吗

health1hp1无关。如果hp1被覆盖、删除、扔掉,或者它发生了什么事,health1不在乎。你知道吗


如果您非常希望向此变量传递引用,可以围绕int类型创建包装类:

class IntWrapper(object):
     def __init__(self, value):
          self.value = value
     def __add__(self, value):
          return IntWrapper(self.value + value)
     def __iadd__(self, value):
          self.value += value
          return self
     def __sub__(self, value):
          return IntWrapper(self.value - value)
     def __isub__(self, value):
          self.value -= value
          return self
     def __str__(self):
          return str(self.value)
     def __repr__(self):
          return str(self)

hp1 = IntWrapper(100)
health1 = 'you have', hp1

hp1 -= 50

print hp1          # 50
print health1      # ('you have', 50)

要使用hp1的任何突变自动更改输出,可以使用类:

class Health:
   def __init__(self, health):
       self.health = health
   def __add__(self, val):
       return Health(self.health + val)
   def __sub__(self, val):
       return Health(self.health - val)
   def __repr__(self):
       return "you have {}".format(self.health)

hp1 = Health(100)
hp1 -= 50
print(hp1)

输出:

you have 50

要做您想做的事情,必须使用。这是python中最接近的指针形式。你知道吗

举个例子:

class Health():
    def __init__(self, value):
        self.hp = value

    def __repr__(self):
        return 'You have {}.'.format(self.hp)

health = Health(100)
hp_clone = health
health.hp -= 50

print hp_clone
# Program outputs : You have 50.

你的问题也可能是重复的 Pointers in Python?。你知道吗

其他人已经解释了你程序中发生的事情。你知道吗

相关问题 更多 >