Static class serializable variables in Python

Is it possible to have serializable static class variables or methods in python? As an example, suppose I have the following code snippet:

import pickle
class Sample:
    count = 0 # class variable
    def __init__(self, a1=0, a2=0):
        self.a = a1
        self.b = a2
        Sample.count += 1

#MAIN
f = open("t1.dat", "wb")
d = dict()
for i in range(10):
    s = Sample(i, i*i)
    d[i] = s
pickle.dump(d,f)
print "Sample.count = " + str(Sample.count)
f.close()

Output:

Sample.count = 10

Now I have another reader program similar to the one above:

import pickle
class Sample:
    count = 0 # class variable
    def __init__(self, a1=0, a2=0):
        self.a = a1
        self.b = a2
        Sample.count += 1

#MAIN
f = open("t1.dat", "rb")
d = pickle.load(f)
print "Sample.count = " + str(Sample.count)

Output:

Sample.count = 0

My question is: How to load a class variable from my file? In other words, how do I serialize a class variable? If it’s directly impossible, is there an alternative? Please suggest. Since the class variable cannot be selected, as an alternative, I used the code fragment in the main part when reading from the file, as shown below:

#MAIN
f = open("t1.dat", "rb")
d = pickle.load(f)
Sample.count = len(d.values())
print "Sample.count = " + str(Sample.count)

Now the conclusion:

Sample.count = 10

Is this an acceptable solution? Any other alternative?

+4
1

?

, , . , , attr :

class Foo:
    attr = 'a class attr'

picklestring = pickle.dumps(Foo)

attr, count, , . "" Sample.count, , .

Sample.count _count Sample.count = self._count. , , d dict, . , .

__setstate__ , (, _count), ( ) __getstate__. (Edit: , count getstate , .)

, yuck: dict d, . , Sample.count = d['_count']. , pickle.dump(d,f), , d['_count'] = Sample.count.

: Sample.count, , (d), Sample s.

: Sample.count = len(d.values()), , , attr .

+3

Source: https://habr.com/ru/post/1620706/


All Articles