'Extend python class in one file so it can be imported and used by class in another file
I have the following modules in python which I downloaded using pip.
mainmodule
|
|--utils
| |
| |--search_obj.py
|
|--search.py
The search looks like this,
import requests
from unidecode import unidecode
from .utils.search_obj import SearchObj
def search_text(text):
..............
..............
and search_obj.py looks like this,
class SearchObj(object):
def __init__(self, name, id, tag):
self.name = name
self.id = id
self.tag = tag
def some functions():
...........
...........
So to execute it I do this,
mainmodule.search.search_text('testword')
It just returns me a SearchObj.
I want to print the name, id and tag.
If I go into the module and create a new function like this,
class SearchObj(object):
def __init__(self, name, id, tag):
self.name = name
self.id = id
self.tag = tag
def print_stuff():
return self.id, self.name, self.tag
Then try,
mainmodule.search.search_text('testword').print_stuff()
I can see the name, id and tag.
I don't want to go in and modify the function this way.
Is there a way I can import the module and just add this extra function so that the search file can access this new function?
I tried this,
class finder (SearchObj):
def __init__(self):
super(SearchObj, self)
def print_stuff(self):
return self.tag, self.name, self.id
But I keep getting an error, when I run this.
finder.search.search_text('testword').print_stuff()
This is the error,
AttributeError: type object 'finder' has no attribute 'search'
Solution 1:[1]
Your post says that this: mainmodule.search.search_text('testword').print_stuff() returns the id, name and tag so you can see it, so it follows that:
s = mainmodule.search.search_text('testword')
will return an instance of SearchObj.
Now you can do: print(s.id) to see the id, or modify that instance using: s.name = 'new name' etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quamrana |
