Posts for: #Python

Enforcing Function Implementation in Subclasses

This is going to get very weird, very quickly. When you create a class in Python, it looks about like the following:

class MyClass:
    pass

Now, let’s say I create some really cool class, with a set of cool functions, but I expect my users to implement some of the functions:

from abc import abstractmethod

class BaseClass:
    @abstractmethod
    def foo(self,):
        raise NotImplementedError

So the intention is, when my user inherits the above class, they do the following:

[Read more]

Managed Attributes in Python

In a previous post, I detailed how to maintain encapsulation using Python’s property. In this piece, I go through how/why to manage and apply validation to class attributes in an object-oriented fashion by means of a fairly plausible example.

A type is the parent class of class, therefore any class is actually a sub-type of type. The following are equivalent:

a = int(8)
a = 8
type(a) # python knows to create an int without being explicit
    int

The point of implementing custom attribute types is (in my case), for validation. The general pattern for creating a class that serves as a type to validate instance attributes is as follows (for a descriptor):

[Read more]