Python 2.7 Class如何从Mixin中获取变量并在Mixin

时间:2017-02-03 04:43:16

标签: python class oop object mixins

我如何使用Mixin来获取不断更改的数据以便流经我的其他类,这样我就可以访问数据而无需与所有类/对象中的类实例相关联?

示例

class DataMixin(object):
  data = {}

  def change_data(self, data=None):
    """
    HERE I AM TRYING TO ASSIGN data TO THE MIXIN ITSELF SO ALL CLASSES
    USING THIS MIXIN RECEIVE THE SAME UPDATED data FIELD
    """
    super(DataMixin, self).data = data


dm = DataMixin()

# EDIT. Moved Below line lower.
# dm.change_data(data={'new': 'data'})


class Class1(DataMixin, object):
  def __init__(self):
    self.data = super(Class1, self).data


class Class2(DataMixin, object):
  def __init__(self):
    self.data = super(Class2, self).data


c1 = Class1()
c2 = Class2()

# EDIT. MOVED TO HERE.
dm.change_data(data={'new': 'data'})

print "c1: {}".format(c1.data)
print "c2: {}".format(c2.data)

以上代码打印:

  

c1:{}

     

c2:{}

我想要打印:

  

c1:{'new':'data'}

     

c2:{'new':'data'}

有没有办法使用Mixins进行上述操作? “要么” 我需要更好地解决这个问题吗?请解释是否应该采取更好的方式。

干杯...

1 个答案:

答案 0 :(得分:0)

这是因为dm是类DataMixin和c1的实例,c2不能从实例继承数据值。如果你想要c1,c2从父类DataMixin继承属性'data',你可以将函数change_data设为classmethod,如下所示

    @classmethod   
    def change_data(self, data=None):
    """
    HERE I AM TRYING TO ASSIGN data TO THE MIXIN ITSELF SO ALL CLASSES
    USING THIS MIXIN RECEIVE THE SAME UPDATED data FIELD
    """
    self.data = data