[Note] A story about trying to override a class method with two underscores in Python 3 series.

A story when I was addicted to a project using Python 3 series.

Suppose you have a class like this


import threading


class ThreadRunner(object):
    def __init__(self):
        self.__thread = None
        self.__event = threading.Event()

    def start(self):
        self.__event.clear()
        self.__thread = threading.Thread(self.__run)

    def stop(self):
        self.__event.set()
        self.__thread.join()
        self.__thread = None

    def is_running(self):
        return not self.__event.is_set()

    def __run(self):
        raise NotImplementedError("class is abstract.")

It is a very simple utility that combines Thread () and Event () of threading. Have the child class override __run () and The processing part was unimplemented so that it could be used nicely.

I actually inherited it and tried to move it.

import time
from .ThreadRunner import ThreadRunner


class TimeWaiter(ThreadRunner):
    def __init__(self):
        super().__init__()

    def __run(self):
        while True:
            #Some processing
            time.sleep(1)

↑ Inherit like this,

from TimeWaiter import TimeWaiter

waiter = TimeWaiter()
waiter.start()

Now.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Program Files\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:\test\ThreadRunner.py", line 23, in __run
    raise NotImplementedError("class is abstract.")
NotImplementedError: class is abstract.

I spit out an error. It should have been overridden and disabled The process of throwing NotImplementedError () of the parent method is called.

Functions / variables with two underscores at the beginning seem to be a little special

When I searched for information from one end, I arrived at the following article.

[Note] About the role of underscore "_" in Python http://qiita.com/ikki8412/items/ab482690170a3eac8c76

About naming Python variables and methods (underscore) https://teratail.com/questions/41277

In the comment section of the first article and the answer of the second article, there was an answer to what I was moss. If you add two underscores to the beginning of the function name or variable name, The name will change automatically inside (it seems to be called mangling), and it will be different.

class ThreadRunner(object):
    def __init__(self):
        self.__thread = None
        self.__event = threading.Event()

    def start(self):
        self.__event.clear()
        self.__thread = threading.Thread(self.__run)

    def stop(self):
        self.__event.set()
        self.__thread.join()
        self.__thread = None

    def is_running(self):
        return not self.__event.is_set()

    def __run(self):
        raise NotImplementedError("class is abstract.")

The ThreadRunner class mentioned earlier is synonymous with the following.


class TimeWaiter(object):
    def __init__(self):
        self.__thread = None
        self.__event = threading.Event()

    def start(self):
        self.__event.clear()
        self.__thread = threading.Thread(self.ThreadRunner__run)

    def stop(self):
        self.__event.set()
        self.__thread.join()
        self.__thread = None

    def is_running(self):
        return not self.__event.is_set()

    def ThreadRunner__run(self):
        raise NotImplementedError("class is abstract.")

    def TimeWaiter__run(self):
        while True:
            #Some processing
            time.sleep(1)

No matter how much the child class inherits, the name will change on the parent class side. It wasn't supposed to be overridden.

In this case, it seemed better to have one underscore. By making one underscore, mangle ring does not work, It will be treated as an override internally.

For those who are familiar with Python, it's natural ... I've just started touching it, so I was quite addicted to it and melted my time ...

That's all for the memorandum.

Recommended Posts

[Note] A story about trying to override a class method with two underscores in Python 3 series.
A story about trying to implement a private variable in Python.
A confusing story with two ways to implement XGBoost in Python + overall notes
A story about trying a (Golang +) Python monorepo with Bazel
A story about trying to introduce Linter in the middle of a Python (Flask) project
A story about how to specify a relative path in python.
How to use the __call__ method in a Python class
[python] A note when trying to use numpy with Cython
[Django] A story about getting stuck in a swamp trying to validate a zip with form [TDD]
A story about adding a REST API to a daemon made with Python
A story about trying to run multiple python versions (Mac edition)
Trying to handle SQLite3 with Python [Note]
[Note] Create a one-line timezone class with python
Data analysis in Python: A note about line_profiler
[Note] A story about not being able to break through a proxy with pip
[Python] Created a class to play sin waves in the background with pyaudio
How to convert / restore a string with [] in python
A story about making 3D space recognition with Python
A story about making Hanon-like sheet music with Python
I want to work with a robot in python.
Things to note when initializing a list in Python
[Python] Created a method to convert radix in 1 second
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
I got stuck when trying to specify a relative path with relative_to () in python
A story about a Python beginner trying to get Google search results using the API
I tried to create a class to search files with Python's Glob method in VBA
How to use python multiprocessing (continued 3) apply_async in class with Pool as a member
A note about hitting the Facebook API with the Python SDK
I made a package to filter time series with python
A story about competing with a friend in Othello AI Preparation
I made a class to get the analysis result by MeCab in ndarray with python
I tried "How to get a method decorated in Python"
A story about an amateur making a breakout with python (kivy) ②
A story about how to deal with the CORS problem
How to build a python2.7 series development environment with Vagrant
Machine learning A story about people who are not familiar with GBDT using GBDT in Python
A story about an amateur making a breakout with python (kivy) ①
A story about trying to use cron on a Raspberry Pi and getting stuck in space
How to override a user-defined method generated by python swig
A note about [python] __debug__
A story about a python beginner stuck with No module named'http.server'
A story that didn't work when I tried to log in with the Python requests module
A story about everything from data collection to AI development and Web application release in Python (3. AI development)
A note on what you did to use Flycheck with Python
[Road to Python Intermediate] Call a class instance like a function with __call__
A story about trying to automate a chot when cooking for yourself
How to create a heatmap with an arbitrary domain in Python
A story about developing a soft type with Firestore + Python + OpenAPI + Typescript
How to write a Python class
Python: A Note About Classes 1 "Abstract"
A note about get_scorer in sklearn
[Python] Inherit a class with class variables
A note about mock (Python mock library)
A story about trying to improve the testing process of a system written in C language for 20 years
A story about trying to run JavaScripthon on Windows and giving up.
[Small story] How to save matplotlib graphs in a batch with Jupyter
A story about a beginner making a VTuber notification bot from scratch in Python
Note: [Python3] Convert datetime to a string in any format you like
A story I was addicted to trying to get a video url with tweepy
[Python / Pandas] A bug occurs when trying to replace a DataFrame with `None` with` replace`
A memo corresponding to Django's runserver moss in Python 2.7.11 entered with Homebrew