Override __init__ of third party library parent class in python - python

I have the current (simplified) code structure:
########### 3rd party library ##############
class LibraryClassA:
def __int__(self):
pass
class LibraryClassB(LibraryClassA):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
def func(self):
print("Do something")
###########################################
class UserDefinedClass(LibraryClassB):
def new_init(self):
print("The new init function")
def func(self):
print("Do something else")
def main():
class = UserDefinedClass(cfg="CONF")
Basically I want to override the original init function of the LibraryClassB (that is a third party library class) and use a new init function defined in my class UserDefinedClass.
Is there a way to do so?

Related

Cross Class Subclass use

I am experimenting with python object orientated programming. Of course I learned about inheritence and so on, but this question is very specific and I couldn't find the answer anywhere yet.
Let's say we have a class class mainClass:. In this class there is a function def func(self):. And within this function func() I want to use two custom classes. Can I and how can I use the first custom class within the second one? (Here's a example)
class custom1:
def func1(self):
#do something
class custom2:
def func2(self):
#call function func1 from class custom1 without creating another instance
class mainClass:
def func(self):
obj1 = custom1()
obj2 = custom2()
obj2.func2()
Like I said I don't want to create a second instance of custom1 within custom2. Only the one in mainClass.
Thanks for your answers :)
what about passing it via the constructor of the first class?
class custom1:
def func1(self):
#do something
class custom2:
def __init__(self, obj1):
self._obj1 = obj1
def func2(self):
self._obj1.func1()
class mainClass:
def func(self):
obj1 = custom1()
obj2 = custom2(obj1)
obj2.func2()

Create a class function that is called whenever another class function is called Python

I'd like to have a class that contains a function that is called whenever another class function is called. And the tricky part is that I'd like this to work for derived classes.
Let's say:
def class A:
def __init__(self):
pass
def b(self):
print("Hello")
and
def class B(A):
def __special_method__(self):
print("Before Hello")
And calling object.b() would print
Before Hello
Hello
Is this even possible?

Inheriting a class from another file

Suppose I have backend.py file and inside is:
class Database():
def __init__(self):
pass
def printDatabase(self):
print('Printing test')
And suppose I have another fie called frontend.py
import backend
class Tester(backend.Database):
def __init__(self):
pass
def testInheritance(self):
self.printDatabase()
Is this the correct code to inherit a class from another file, and use one of its methods?

Store method from class in new file

I have a Python project where most business logic is in class methods. Now I would like to reuse some of the class methods in an independent project.
Is it possible to write a class method that 'exports' other class methods to a new Python file to create a script with a bunch of exported functions?
class MyObject:
def __init__(self, value):
self.value = value
def method1(self):
# the method I want to use in another project
def method2(self):
...
def method3(self):
...
def export_method(self, target_file):
# export the code of method1 to a new python file
When I run export_method('myfile.py') I would like to create a Python file that contains method1 as a function:
def method1():
...
Note: I understand that the software should be restructured and method1 should be in another module where it can be imported from other projects. I'm just curious if there is a simple way to access the code of a Python program from the code itself.
Use inspect:
Either directly:
import inspect
lines = inspect.getsource(MyObject.method1)
with open(target_file, 'w') as file:
file.write(lines)
Or if you prefer to get it as a class method and print all methods in the class:
import inspect
class MyObject:
def __init__(self, value):
self.value = value
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
#classmethod
def export_method(cls, target_file):
# export the code of method1 to a new python file
methods = inspect.getmembers(cls, predicate=inspect.ismethod)
with open(target_file, 'w') as f:
for method in methods:
lines = inspect.getsource(method[1])
f.write(lines)
Because of the #classmethod decorator the following is allowed:
MyObject.export_method('code.txt')

Use getattr from a Mixin class that lives in a different module to get a class from the caller

I have a Mixin class the lives in myModule.mixins. A new class in myModule.main (MyPaternalClass) is inheriting from myModule.mixins.MyMixin.
The purpose of this mixin is to generate new "child" objects given a string with the name of the child class, but the classes for these objects live in myModule.main, not in myModule.mixins
I understand how to do this when the Mixin lives in the same module using:
this = sys.modules[__name__]
cls = getattr(this, objType)
new_cls_inst = cls()
However I'm having trouble finding a good way to do this when the mixin class lives in its own module.
ex. myModule.mixins
class MyMixin(object):
def new_obj(self, objType):
cls = #Get the class
newobj = cls()
return newobj
Now, this mixin would be used in the following:
ex. myModule.main
from .mixin import MyMixin
class MyPaternalClass(MyMixin):
def __init__(self):
super(MyPaternalClass, self).__init__()
self.children = []
def add_child(self, child_type):
self.children.append(self.new_obj(child_type))
class Son(object):
def __init__(self):
pass
class Daughter(object):
def __init__(self):
pass
The usage would look similar to this:
new_parent = MyPaternalClass()
new_parent.add_child('Son')
new_parent.add_child('Daughter')
The reason the mixin class can't live in the same module is because it's intended to be used generically in several other modules.

Categories

Resources