如何更改变量内的变量?

问题描述 投票:-2回答:5

这是我的代码:

hp1 = 100
health1 = 'you have', hp1

hp1 = hp1 - 50
health1

print hp1
print health1

这是它打印的内容:

50
('you have', 100)

为什么hp1不会改变健康状况?

python
5个回答
0
投票

要做你想做的事,你必须使用一个班级。这是你将在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?的副本。

您的计划中发生的事情已由其他人解释。


2
投票

要使用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

2
投票

以下行:

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)

0
投票

因为你定义了health1 - 一个(string, int)元组 - 因为hp1仍然是100并且从那以后没有改变它。这不是C / C ++意义上的指针,只是按值复制。


0
投票

你的代码就是这样做的,

hp1 = 100 # setting hp1 as 100
health1 = 'you have', hp1 # making a tuple 

hp1 = hp1 - 50 # subracting 50 from hp1 -> gives 50 as result
health1 # simply calling health1

print hp1 # displaying hp1
print health1 # displaying health1

在这段代码中,

你将hp1定义为100,让它存储在一个位置1000

你创建了一个元组,将health1命名为'you have', hp1。它将存储在一个位置说2000

你从hp1中减去50,使得hp1 50,这将不会改变health1变量,因为它存储在不同的位置。但它会改变hp1的价值

希望这可以帮助。!!

© www.soinside.com 2019 - 2024. All rights reserved.