Beorn
Beorn

Reputation: 437

How to save the current state in instance of object?

I want to create a class which will have a method to reset it's properties, but I need the data from before the reset to be saved in some list.

I tried the following code:

class Foo:
  feature1 = 'hey'
  feature2 = 10

  def reset(self):
      self.feature1 = None
      self.feature2 = None


some_list = []

foo = Foo()
print(foo.feature1)
print(some_list)
some_list.append(foo)
foo.reset()
print(foo.feature1)
print(some_list[0].feature1, some_list[0].feature2)

But it prints this:

hey
[]
None
None None

Is there a way to copy it ?

Upvotes: 1

Views: 667

Answers (4)

Daniel
Daniel

Reputation: 42748

You should not try to reset instances, because there could be many references to this instance. Instead, create a new one, if you need a fresh object:

class Foo:
    def __init__(self, feature1=None, feature2=None):
        self.feature1 = feature1
        self.feature2 = feature2


some_list = []

foo = Foo("hey", 10)
print(foo.feature1)
print(some_list)
some_list.append(foo)
foo = Foo()
print(foo.feature1)
print(some_list[0].feature1, some_list[0].feature2)

Output:

hey
[]
None
hey 10

Upvotes: 1

Ralf
Ralf

Reputation: 16495

I suggest you try creating new instances instead of reseting. And also make the attributes part of the instance, not the class.

Defining your class like this:

class Foo:
    def __init__(self):
        self.feature1 = 'hey'
        self.feature2 = 10

    def __repr__(self):
        return '[{}|{}]'.format(self.feature1, self.feature2)

And then running these lines:

some_list = []

foo = Foo()
foo.feature1 = 'hey_1'
some_list.append(foo)
print(some_list)

foo = Foo()            # will be a new instance
foo.feature1 = 'hey_2'
some_list.append(foo)
print(some_list)

You get this output:

[[hey_1|10]]
[[hey_1|10], [hey_2|10]]

Upvotes: 2

ramazan polat
ramazan polat

Reputation: 7880

Know the difference between class attributes and object attributes.

feature1 and feature2 are both class attributes. That means you can access them as Foo.feature1 and Foo.feature2.

When you use self.feature1, you are referring to object attributes. In your case, if there is no object attribute defined as feature1, you will get class attribute because of inheritance.

On the other hand, if you defined an object attribute in with same name as class attribute, using self gives you object attribute, not class attribute. If you want to access class attributes explicitly in an object, you should use className.attribute, in your case Foo.feature1.

Upvotes: 0

Jiaqi Guo
Jiaqi Guo

Reputation: 61

Make a copy of the object before reset and then append the copy into list not the original object.

Based on your demand, use deepcopy is a better way since I think you are doing a snapshot or similar things.

Upvotes: 0

Related Questions