vendredi 6 juillet 2018

Passing object reference to multiple classes in Python

I am not sure whether you can understand this problem with above title or not. dont worry. here is the explaination to my problem.

i have few objects of class Field, and few rules objects [each rule from different class say RuleA, RuleB, RuleC, ... ]

i want to send each all fields objects to each rule object. if one rule modifies field object attribute, it should reflect in all other rules

class Field:
  a = 2
  b = 3
  # and few more attributes

field_count = 10 #let say i have 10 fields
fields = [Field() for i in range(field_count)]

class RuleA:
  def __init__(self, fields):
    self.fields = fields
  def process(self):
    self.fields[2].a = 61

class RuleB:
  def __init__(self.fields):
    self.fields = fields
  def process(self):
    print(self.fields[2].a)

..... other rules .....    

rule_a_obj = RuleA(fields)
rule_b_obj = RuleB(fields)

..... other rules initialization .....

rule_a_obj.process()
rule_a_obj.process() # should print 61

any suggestions/ideas to achieve this

Aucun commentaire:

Enregistrer un commentaire