Is there a way to ignore part of __init__() method while super() in Python3?

Viewed 108

I'm considering if there is a way to use inherit with super() in Python3 but ignore part of the method? I can show you an example below.

Let's say I have class that initialize some RPi GPIOs

class Encoder(object):
    def __init__(self, A, B):
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(A, GPIO.IN)
        GPIO.setup(B, GPIO.IN)
        self.A = A
        self.B = B

I would like to inherit this class and its init() method, but I would like to change GPIO.setmode(GPIO.BCM) to GPIO.setmode(GPIO.BOARD). Is there a way to do it without copy whole __init__ into my child class?

It is not a big deal to just copy it with change in this one line, but I'm curious if it is possible to avoid copy-pasting ;)

2 Answers

as @tdalaney said if you can edit the Encoder source code you could:

class Encoder(object):
    def __init__(self, A, B, kwarg=GPIO.BCM):
        GPIO.setmode(kwarg)
        GPIO.setup(A, GPIO.IN)
        GPIO.setup(B, GPIO.IN)
        self.A = A
        self.B = B

and then in the subclass

class subclass:
    def __init__(self, A,, B, ...):
        super().__init__(A, B, kwarg=GPIO.BOARD)

I found another option buts its not vary nice. In python you can use the inspect module to read a functions source code. using this you can than edit it to suit your needs. This assumes you know which line to change. You could do it as follows:

import inspect

class A:
    def __init__(self):
        self.var1 = 1
        self.var2 = 2
        self.var3 = 3

class B(A):
    def __init__(self):
        code = inspect.getsource(A.__init__).split("\n")[1:]
        code = deTab(code)
        code[1] = "self.var2 = 10"
        code = rebuild(code)
        exec(code)

def deTab(code):
    count = 0
    for space in code[0]:
        if space != " ":
            break
        count+=1
    return [line[count:] for line in code]

def rebuild(code):
    return "".join([line+"\n" for line in code])

a = A()
b = B()
Related