Programming improvements 2

A few things of the many things I learned last weeks in Python.

This is what I used to do to conditionally set settings:

class MyClass:
    def method(self, args**):
        <some code block>
        if some_arg == "condition":
            self.option = "this setting"
            <run some code>
            <call a method>
        else:
            self.option = "another setting"
            <run some other code>
            <call a different method>
        <some more code block>

myclass = MyClass()
myclass.method(args)

And it could be much more complicated.

Using an object oriented approach, can be so much nicer.

class MyBaseClass:
    def method(self, args**):
        <some code block>
        self._submethod(subargs**)
        <some more code block>
    @abstractmethod
    def _submethod():
        pass

The private submethod would then be defined in the child classes. First for “condition”

class MyClass_condiontion(MyBaseClass):
    def _submethod()::
        self.option = "this setting"
        <run some code>
        <call a method>     # can be in this or the parent class

Second for the else:

class MyClass_else_condiontion(MyBaseClass):
    def _submethod()::
        self.option = "another setting"
        <run some other code>
        <call a different method>     # can be in this or the parent class

To call the classes one could use the condition:

if some_arg == "condition":
    myclass = MyClass_condiontion()
else:
    myclass = MyClass_else_condiontion()
myclass.method(args)

With this approach the coding is so much neater. Each method knows what it has to do and there is no fuss about the settings.

While I still feel, it would have been nice, if I’d have learned these little things before (which comes from the thought I would be liked more, and from the expectation of perfectionism by me and because of that I also think others expect perfectionism from me – which is just not achievable), it is nice to pick new things up now. While I thought in my 20s that in many areas of life I can stop learning at some point, in the last years I learned that learning will never end in any part of life, and that is good! Because if I stop being willing to learn, I will go backwards.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s