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

Assigning (instead of defining) a __getitem__ magic method breaks indexing [duplicate]

Special methods (essentially anything with two underscores on each end) have to be defined on the class. The internal lookup procedure for special methods completely skips the instance dict. Among other things, this is so if you do class Foo(object): def __repr__(self): return ‘Foo()’ the __repr__ method you defined is only used for instances of … Read more

Why isn’t my class initialized by “def __int__” or “def _init_”? Why do I get a “takes no arguments” TypeError, or an AttributeError?

What do the exception messages mean, and how do they relate to the problem? As one might guess, a TypeError is an Error that has to do with the Type of something. In this case, the meaning is a bit strained: Python also uses this error type for function calls where the arguments (the things … Read more

scala slick method I can not understand so far

[UPDATE] – added (yet another) explanation on for comprehensions The * method: This returns the default projection – which is how you describe: ‘all the columns (or computed values) I am usually interested’ in. Your table could have several fields; you only need a subset for your default projection. The default projection must match the … 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

Why does Python use ‘magic methods’?

AFAIK, len is special in this respect and has historical roots. Here’s a quote from the FAQ: Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))? The major reason is history. Functions were used for those operations that were generic for a group of types and which were … Read more

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