S
S
Sergey Bard2018-05-05 08:22:41
Python
Sergey Bard, 2018-05-05 08:22:41

How to call a method from a child class from a base class?

Hello everyone, please help, there is such a class

import paramiko
import time
import subprocess
import telnetlib

class Base(object):
    def __init__(self, args):
        self.args = args

    def __enter__(self):
        self.con = self._connect()
        return self.con

    def __exit__(self, type, value, traceback):
        self.con.close()

    def run(self, *args, **kwargs):
        raise NotImplementedError('Abstract method not implemented.')

    def _connect(self, **kwargs):
        raise NotImplementedError('Abstract method not implemented.')

class Paramiko(Base):
    def __init__(self, args):
        Base.__init__(self, args)

    def _connect(self):
            self.con = paramiko.SSHClient()
            self.con.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.con.connect(hostname=self.args.host, port=self.args.port, username=self.args.user, password=self.args.password)
            return self.con

    def _response(self, channel):
        while not channel.recv_ready():
            time.sleep(0.1)
        stdout = ''
        while channel.recv_ready():
            stdout += channel.recv(1024)
        return stdout

    def _send_connect(self, cmd):
        with Base(self.args) as connect:
            channel = connect.invoke_shell()
            self._response(channel)
            channel.send(cmd+'\n')
            return self._response(channel)

    def run(self, cmd):
        try:
            return(self._send_connect(cmd))
        except paramiko.ssh_exception.AuthenticationException as e:
            return(e)

I call it from another class,
Paramiko(args).run(cmd)
as you can see, Base is the base class for Paramiko, please tell me how to make it so that when I call the __enter__ method in the base class, which has a self._connect() call, the _connect() method from the child would work class i.e. Paramiko, and if it is not there, then throw out Abstract method not implemented. from base.
I hope I clearly wrote what I need), thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alexalexes, 2018-05-05
@alexalexes

Overload the __enter__ method in the Paramiko class.

L
lega, 2018-05-05
@lega

This is how it originally works.

Python 2.7

>>> class Base(object):
...   def from_base(self):
...     self.from_child()
...   def from_child():
...     raise NotImplementedError
... 
>>> class Child(Base):
...   def from_child(self):
...     print('child!')
... 
>>> child = Child()
>>> child.from_base()
child!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question