Reputation: 11
I'm currently trying to write a piece of code that will dump all attributes of a given class instance to a dictionary so that I can change them without changing the source object. Is there a method for doing this, or perhaps a built-in dictionary I can copy and access?
What I'm really doing is making a special class that copies the actual attributes (and their corresponding values) from instances of varying other classes. Basically it would mimic any instance of any class.
For example, object x has attributes x.name and x.number, "Joe" and 7, respectively. I want my new object mimic, object y, to copy the attributes so that y now has attributes y.name and y.number, "Joe" and 7.
Thanks!
EDIT: I found what I was looking for shortly after posting this!
Python dictionary from an object's fields
That's pretty much all I needed to know.
Upvotes: 1
Views: 533
Reputation: 184151
Why not write a __getattr__()
(or __getattribute__()
) method on your "mimic" object that does this only when an attribute is requested, rather than copying the attributes? Among other benefits, this will keep properties as executable code (rather than copying their return value) and will work even if a new attribute is added to the mimicked object after you create the mimic object. (Also, I would call it a wrapper or proxy object rather than a mimic.) Something like:
class Wrapper(object):
def __init__(self, obj):
self.__wrapped__ = obj
def __getattr__(self, key):
return getattr(self.__wrapped__, key)
l = [3, 2, 1]
w = Wrapper(l)
print w.index(2) # calls through to l.index()
Upvotes: 2
Reputation: 11547
Very object has a __dict__
attribute that maps names (variables) to the values they are bound to. Muck around with that.
>>> class MyObj(object):
... def __init__(self, x, y):
... self.x = x
... self.y = y
...
>>> foo = MyObj('Joe', 7)
>>> foo.x
'Joe'
>>> foo.y
7
>>> foo.__dict__
{'y': 7, 'x': 'Joe'}
>>> class Mimic(object):
... def __init__(self, obj):
... self.__dict__.update(obj.__dict__)
...
>>> m = Mimic(foo)
>>> m.x
'Joe'
>>> m.y
7
>>> print m.__dict__
{'y': 7, 'x': 'Joe'}
>>>
Upvotes: 1