如何使不同的变量引用相同的值,同时仍然允许直接操作?

2024-10-02 02:31:02 发布

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

让不同的变量引用相同的值,同时仍然允许对值进行直接操作(例如*)的好方法是什么?你知道吗

所需代码的示例是能够执行以下操作:

a = <Reference to integer 2>
b = a
print(a * b)  # Should show 4
<a update (not with assign using =) with reference to integer 3>
print(a * b)  # Should show 9

不太理想的解决方案是为值使用容器,如namespace、list、dict等,但这需要引用下面的.value等属性,因此不太理想:

import types

a = types.SimpleNamespace(value = 2)
b = a
print(a.value * b.value)  # Should show 4
a.value = 3
print(a.value * b.value)  # Should show 9

封装值的好方法是什么,这样直接操作仍然是可能的?你知道吗


Tags: to方法代码示例valueshowwithupdate
3条回答

你想要的行为可以用一个类来模拟,尽管有点笨拙和不雅:

class reference:
  def __init__(self, num): self.num = num
  def get(self): return self.num
  def set(self, num): self.num = num
  def __mul__(self, other): return self.num * other
  def __div__(self, other): return self.num / other
  def __add__(self, other): return self.num + other
  def __sub__(self, other): return self.num - other

在这些运算符过载的情况下,将出现以下情况:

a = reference(5)
b = a
print a.get()
print a * 4

印刷品

5
20

我意识到如果你想引用不同的类型,这是相当麻烦的,因为你必须为每一个类型重载你需要的操作符,但是这是最接近于模拟指针的。你知道吗


或者,您可以在reference类中只包含getset__init__,然后添加稍后需要的重载函数:

class reference:
  def __init__(self, num): self.num = num
  def get(self): return self.num
  def set(self, num): self.num = num

a = reference(5)
reference.__mul__ = lambda self, num: self.num * num
print a * 4

以上打印20

class Manager:
     def __init__(self,data):
         self.__dict__["data"] = data
     def __getattr__(self,attr):
         return getattr(self.data,attr)
     def __setattr__(self,attr,val):
         return setattr(self.data,attr,val)
     def set(self,val):
         self.__dict__["data"] = val


master = Manager(55)
print print master+5
print slave = master
print slave.set(88)
print slave + 10
print master+2

...
master_s = Manager("Test")
print master_s + " String"

...

master_c = Manager(MyCustomClass())
master_c.do_my_method()

也许吧?你知道吗

您可以创建一个重写乘法运算的类。你知道吗

class Reference:
    def __init__(self, value):
        self.value = value
    def __mul__(self, other):
        return Reference(self.value * other.value)

这将允许您直接将引用彼此相乘。例如,Reference(3) * Reference(4)产生Reference(12)。你知道吗

您可能需要重写__rmul__和所有其他数值运算。^{}中的抽象类可能对确保您不会忘记任何抽象类很有用。你知道吗

相关问题 更多 >

    热门问题