Simple example of use of __setstate__ and __getstate__

Here’s a very simple example for Python that should supplement the pickle docs. class Foo(object): def __init__(self, val=2): self.val = val def __getstate__(self): print(“I’m being pickled”) self.val *= 2 return self.__dict__ def __setstate__(self, d): print(“I’m being unpickled with these values: ” + repr(d)) self.__dict__ = d self.val *= 3 import pickle f = Foo() f_data … Read more

Python __call__ special method practical example

This example uses memoization, basically storing values in a table (dictionary in this case) so you can look them up later instead of recalculating them. Here we use a simple class with a __call__ method to calculate factorials (through a callable object) instead of a factorial function that contains a static variable (as that’s not … Read more

What is the difference between __str__ and __repr__?

Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ Default implementation is … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)