How to subclass Python list without type problems?

Firstly, I recommend you follow Björn Pollex’s advice (+1). To get past this particular problem (type(l2 + l3) == CustomList), you need to implement a custom __add__(): def __add__(self, rhs): return CustomList(list.__add__(self, rhs)) And for extended slicing: def __getitem__(self, item): result = list.__getitem__(self, item) try: return CustomList(result) except TypeError: return result I also recommend… pydoc … Read more

Reclassing an instance in Python

Reclassing instances like this is done in Mercurial (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called repo and is initially a localrepo instance. It is passed to each extension in turn and, when needed, extensions will define a new class which … Read more

Rotating a view in layoutSubviews

The problem with the code in the question seems to be that the transformations keep getting added to each other. In order to fix this, the solution is to reset the transformations every time, that is, set it to the identity transform. rotationView.transform = CGAffineTransformIdentity Here is a partial implementation that shows the key parts. … Read more

Why can’t I subclass datetime.date?

Regarding several other answers, this doesn’t have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc. >>> import datetime >>> class D(datetime.date): def __new__(cls, … Read more

Subclassing dict: should dict.__init__() be called?

You should probably call dict.__init__(self) when subclassing; in fact, you don’t know what’s happening precisely in dict (since it’s a builtin), and that might vary across versions and implementations. Not calling it may result in improper behaviour, since you can’t know where dict is holding its internal data structures. By the way, you didn’t tell … Read more

Subclass dict: UserDict, dict or ABC?

If you want a custom collection that actually holds the data, subclass dict. This is especially useful if you want to extend the interface (e.g., add methods). None of the built-in methods will call your custom __getitem__ / __setitem__, though. If you need total control over these, create a custom class that implements the collections.MutableMapping … Read more