ansh2111
ansh2111

Reputation: 21

How do I initialize a new python object with existing object and a new parameter value in python?

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.

Upvotes: 0

Views: 485

Answers (1)

ansh2111
ansh2111

Reputation: 21

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)

Upvotes: 1

Related Questions