Python 通过引用dict传递变量?

Python 通过引用dict传递变量?,python,dictionary,reference,Python,Dictionary,Reference,我想做到以下几点: 我有一个X类,还有许多不同的其他类(a、B、C等)。 类X有一个方法,所有其他类都可以使用该方法将它们的一些变量发布到类X 在类X中,我想在字典中收集所有这些变量 我希望该字典始终具有另一个类传递的变量的当前值,而不必再次发布另一个类中的特定变量。 例如: class X: def __init__(self): self.d = {} def add_to_dict(self, var_name, var): # obvio

我想做到以下几点:

我有一个X类,还有许多不同的其他类(a、B、C等)。 类X有一个方法,所有其他类都可以使用该方法将它们的一些变量发布到类X

在类X中,我想在字典中收集所有这些变量

我希望该字典始终具有另一个类传递的变量的当前值,而不必再次发布另一个类中的特定变量。

例如:

class X:
    def __init__(self):
        self.d = {}

    def add_to_dict(self, var_name, var):
        # obviously this is the point, where it fails - I want somehow that a 
        # reference to var gets added to the dict, and not just a copy of var
        self.d[var_name] = var   


class A:
    def __init__(self, instance_of_X):
        self.var = 5    # variable which gets updated regularly within A
        self.instance_of_X = instance_of_X

    def publish(self):
        # I want all value changes of var to also be present in X, without
        # updating it by myself
        self.instance_of_X.add_to_dict('var_name', self.var)    
试试这个:

class X:
    def __init__(self):
        self.d = {}

    def add_to_dict(self, var_name, var):
        # obviously this is the point, where it fails - I want somehow that a
        # reference to var gets added to the dict, and not just a copy of var
        self.d[var_name] = var


class A:
    def __init__(self, instance_of_X):
        self.var = 5    # variable which gets updated regularly within A
        self.instance_of_X = instance_of_X

    def publish(self):
        # I want all value changes of var to also be present in X, without
        # updating it by myself
        self.instance_of_X.add_to_dict('var_name', self.var)


x = X()
a = A(x)
a.publish()
print(x.d)

说明:您必须创建A的
var
instance\u of_X
属性,请参见类A的新构造函数。在
A.publish()中调用
instance\u of_X
当然也必须使用该属性。

在Python中不能引用类似的变量。但是,可以通过跟踪对象和感兴趣的属性名称来模拟效果,并将其与
@property
描述符结合使用来调用函数,该函数将在需要时检索属性的当前值

我的意思是:

class X:
    def __init__(self):
        self._d = {}

    def add_to_dict(self, alias, obj, attr_name):
        self._d[alias] = lambda: getattr(obj, attr_name)  # Function to retrieve attr value.

    @property
    def d(self):
        return {alias: get_obj_attr() for alias, get_obj_attr in self._d.items()}


class A:
    def __init__(self, instance_of_X):
        self.var = 5  # Variable which gets updated regularly within A.
        self.instance_of_X = instance_of_X

    def publish(self):
        self.instance_of_X.add_to_dict('var_alias', self, 'var')


x = X()
a = A(x)
a.publish()
print(x.d)  # -> {'var_alias': 5}
a.var = 42
print(x.d)  # -> {'var_alias': 42}

在Python中只能引用对象。你不能引用变量。对不起,这不是我的意思,我的问题中有一些错误,因为我在写问题时没有注意并更正了它们(你认出了它们,谢谢)。我真正想要的是,当A中的变量发生变化时,它也应该在X中更新