0

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_b_obj.process() # should print 61

any suggestions/ideas to achieve this

2
  • 1
    You're calling rule_a_obj.process() twice. Do you mean the second to be rule_b_obj.process()? Because that will print 61 Commented Jul 6, 2018 at 19:24
  • sorry its rule_b_obj. corrected thanks @PatrickHaugh Commented Jul 6, 2018 at 19:29

1 Answer 1

2

A name in python refers to the location where the value is stored, not the value itself (except for base types like numbers). So when you make an assignment, you are copying a reference to the object in question, not a full deep clone of the object itself.

This is easily seen in the following:

my_dict = {'x': 1, 'y': 2}
my_dict_ref = my_dict
my_dict_ref['z'] = 3
print(my_dict) # {'y': 2, 'x': 1, 'z': 3}

So we were able to modify my_dict through the my_dict_ref variable. In your code, you have already achieved this, but you call the process() function of RuleA twice, so your print statement is never called. :)

rule_a_obj.process() # should print 61

should read:

rule_b_obj.process() # should print 61
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.