magic-methods

What is the __dict__.__dict__ attribute of a Python class?

What is the __dict__.__dict__ attribute of a Python class? Question: >>> class A(object): pass … >>> A.__dict__ <dictproxy object at 0x173ef30> >>> A.__dict__.__dict__ Traceback (most recent call last): File “<string>”, line 1, in <fragment> AttributeError: ‘dictproxy’ object has no attribute ‘__dict__’ >>> A.__dict__.copy() {‘__dict__’: <attribute ‘__dict__’ of ‘A’ objects> … } >>> A.__dict__[‘__dict__’] <attribute ‘__dict__’ …

Total answers: 3

Why does Python use 'magic methods'?

Why does Python use 'magic methods'? Question: I’m a bit surprised by Python’s extensive use of ‘magic methods’. For example, in order for a class to declare that instances have a "length", it implements a __len__ method, which it is called when you write len(obj). Why not just define a len method which is called …

Total answers: 8

Simple example of use of __setstate__ and __getstate__

Simple example of use of __setstate__ and __getstate__ Question: I don’t know what the __setstate__ and __getstate__ methods do, so help me with a simple example. Asked By: zjm1126 || Source Answers: These methods are used for controlling how objects are pickled and unpickled by the pickle module. This is usually handled automatically, so unless …

Total answers: 4

What is the difference between __str__ and __repr__?

What is the difference between __str__ and __repr__? Question: What is the difference between __str__ and __repr__ in Python? Asked By: Casebash || Source Answers: From an (An Unofficial) Python Reference Wiki (archive copy) by effbot: __str__ “computes the “informal” string representation of an object. This differs from __repr__ in that it does not have …

Total answers: 28

Where is the Python documentation for the special methods? (__init__, __new__, __len__, …)

Where is the Python documentation for the special methods? (__init__, __new__, __len__, …) Question: Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__, __new__, __len__, __add__) Asked By: mk12 || Source Answers: Please take a look at the special method names section in the Python language …

Total answers: 10

Is there any case where len(someObj) does not call someObj's __len__ function?

Is there any case where len(someObj) does not call someObj's __len__ function? Question: Is there any case where len(someObj) does not call someObj’s __len__ function? I recently replaced the former with the latter in a (sucessful) effort to speed up some code. I want to make sure there’s not some edge case somewhere where len(someObj) …

Total answers: 5