Richard Christensen Richard Christensen - 1 month ago 13
Python Question

Create a new reference to instantiated class in Python

I have a class property that contains a class reference as such

class UserEnvironment(object):
_user = None

def __init__(self, session_id):
self._user = User(session_id)

def create_user(self):
# copy self._user modify the copy and return it without modifying original object.


what I need to do is take self._user and create a new instance from it, then return the reference without modifying the original object. How can I do this?

Answer

First, don't define _user as a class member. Remove the statement or _user will be the same for all class instances. Probably not what you want.

Then, to "clone" the user, just use copy.deepcopy like this;

import copy

class UserEnvironment(object):

    def __init__(self, session_id):
         self._user = User(session_id)

    def create_user(self):
         # copy self._user modify the copy and return it without modifying original object.
         return copy.deepcopy(self._user)