[ad_1]

There’s the old joke about 10 kinds of programmers, but the truth is when it comes to programming, there are often people who make tools and people who use tools. The Arduino system is a good example of this. Most people use it like a C compiler. However, it really uses C++, and if you want to provide “things” to the tool users, you need to create objects. For example, when you put Serial in a program, you use an object someone else wrote. Python — and things like Micropython — have the same kind of division. Python started as a scripting language, but it has added object features, allowing a rich set of tools for scripters to use. [Damilola Oladele] shows the ins and outs of object-oriented Python in a recent post.

Like other languages, Python allows you to organize functions and data into classes and then create instances that belong to that class. Class hierarchies are handy for reusing code, customizing behavior, and — through polymorphism — building device driver-like architectures.

For example, you might build a class for temperature sensors and then create specialized subclasses for different specific sensors. The code to convert the sensor reading to degrees would live in each subclass. However, common code, such as getting an average of several samples, could be used in the main class. Even more importantly, any part of your code that needs a temperature sensor will just deal with the main class and won’t care what kind of sensor is actually in use except, of course, when you instantiate the sensor.

Python’s implementation of object orientation does have a few quirks. For example, if you create a class variable, it can be read from a subclass without specifying scope like you’d expect. But if you try to write to it from a subclass, you create a new variable for that particular subclass, which then hides the parent class version.

Still, objects can make your tools and libraries much more reusable, and Python makes it relatively easy compared to some other languages. If you want to see how objects can improve common constructs like state tables, you’ll have to read a different language. If you want to see an admittedly hairy Python example, check out VectorOS, the operating system for the 2023 Hackaday Supercon badge.

[ad_2]

Leave a Reply

Your email address will not be published. Required fields are marked *