Cast base class to derived class python (or more pythonic way of extending classes)

If you are just adding behavior, and not depending on additional instance values, you can assign to the object’s __class__: from math import pi class Circle(object): def __init__(self, radius): self.radius = radius def area(self): return pi * self.radius**2 class CirclePlus(Circle): def diameter(self): return self.radius*2 def circumference(self): return self.radius*2*pi c = Circle(10) print c.radius print c.area() … Read more

How to dynamically create a derived type in the Python C-API

I encountered the same problem when I was modifying an extension to be compatible with Python 3, and found this page when I was trying to solve it. I did eventually solve it by reading the source code for the Python interpreter, PEP 0384 and the documentation for the C-API. Setting the Py_TPFLAGS_HEAPTYPE flag tells … Read more

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No. A reference to a derived class must actually refer to an instance of the derived class (or null). Otherwise how would you expect it to behave? For example: object o = new object(); string s = (string) o; int i = s.Length; // What can this sensibly do? If you want to be able … Read more

Why does calling a method in my derived class call the base class method?

There’s a difference between new and virtual/override. You can imagine, that a class, when instantiated, is nothing more than a table of pointers, pointing to the actual implementation of its methods. The following image should visualize this pretty well: Now there are different ways, a method can be defined. Each behaves different when it is … Read more

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