0

Here is my code snippet:-

class Board:
    def __init__(self,level):
        self.lvl=level
        self.val=0
class State:
    def __init__(self):
        self.p=Board(0)
        self.p.val=100
        self.u=self.p

I want that u has a level of 1 and val of 100. I know i can modify separately, but i want to pass reference of p while initializing u and a level value 1. Something like self.u=Board(1) would not solve my purpose.

6
  • Make Board accept val as a second parameter…?! self.u = Board(1, 100)…?! Commented Jun 27, 2017 at 14:03
  • That's right but i want to pass reference of p to u so that u.val=p.val. Commented Jun 27, 2017 at 14:09
  • Well then… self.p = self.u = Board(0, 100)…?! But why have two references to the same object in the first place? Commented Jun 27, 2017 at 14:10
  • It's not clear whether you want u.val and p.val to have the same initial value but change independantly or if what you're asking for is that whenever p.val changes u.val changes accordingly... Commented Jun 27, 2017 at 14:13
  • self.p = self.u = Board(0, 100) This would actually go wrong if I am using a list or any other structure with recursion. Simply, the state of u has to be same as p with a level of +1. Commented Jun 27, 2017 at 14:19

1 Answer 1

1

After many tries I thought copy constructor can be used. But I think if reference passing or any easy method exists It would be efficient.

class Board:
    def __init__(self,level,orig=None):
        if orig is None:
            self.val=0
        else:
            self.val=orig.val
        self.lvl=level
class State:
    def __init__(self):
        self.p=Board(0)
        self.p.val=100
        self.u=Board(1,self.p)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.