When should you use a class vs a struct in C++?

The differences between a class and a struct in C++ is: struct members and base classes/structs are public by default. class members and base classes/struts are private by default. Both classes and structs can have a mixture of public, protected and private members, can use inheritance and can have member functions. I would recommend you: … Read more

What __init__ and self do in Python?

In this code: … the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in … Read more

What is an example of the Liskov Substitution Principle?

A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn’t quite work in code. In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The “is a” makes you want to model this with inheritance. However if … Read more

What is Inversion of Control?

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code. For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this: What we’ve done here creates a dependency between the TextEditor and the … Read more

What does ‘super’ do in Python? – difference between super().__init__() and explicit superclass __init__()

The benefits of super() in single-inheritance are minimal — mostly, you don’t have to hard-code the name of the base class into every method that uses its parent methods. However, it’s almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody … Read more

Understanding Python super() with __init__() methods [duplicate]

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven’t already. Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer. The … Read more

What is the purpose of the word ‘self’?

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the … Read more