I have a rather large project, including a class Foo which recently needed to be updated using the @property
decorator to create custom getter and setter methods.
I also stored several instances of Foo
on my hard drive that at some point I might need to reload. My problem is, that I cannot access the attributes decoreted with property on these old objects.
Consider the following example:
import pickle# define Class and create instance
class Foo:def __init__(self):self.val = 1
foo = Foo()# dump foo into file
with open("foo.pickle", 'wb') as handle:pickle.dump(foo, handle, pickle.HIGHEST_PROTOCOL)# overwrite and add @property in the class definition
class Foo:def __init__(self):self._val = "new_foo"@propertydef val(self):return self._val@val.setterdef val(self, val):self._val = valfoo_new = Foo()
print(foo_new.val)# reload foo
with open("foo.pickle", "rb") as handle:foo_old = pickle.load(handle)# try to access attributes
print(foo_old.val)
The last line raises:
NameError: name '_val' is not defined
What options do I have to still access the attributes of my archived instances?
Edit: Changed self.val
to self._val
in the constructor of the second Foo-definition.