- I have an external library which I cannot touch. This library has a function, genA(), that returns the instance of class A.
- In my side I define class B as a subclass of class A.
- I want to use the instance of class B in my project, but the instance should be generated by genA().
Is there any standard and easy way to do this?
# I cannnot tweak these code
def genA():
a = A
return(a)
class A:
def __init__():
self.a = 1
# ---
# code in my side
class B(A):
def __init__():
self.b = 2
a = genA()
# like a copy-constructor, doesn't work
# b = B(a)
# I want to get this
b.a # => 1
b.b # => 2
Here is an equivalent c++ code:
#include <iostream>
// library side code
class A {
public:
int a;
// ... many members
A() { a = 1; }
};
void fa(A a) {
std::cout << a.a << std::endl;
}
A genA() { A a; return a; }
// ///
// my code
class B : public A {
public:
int b;
B() : A() { init(); }
B(A& a) : A(a) { init(); }
void init() { b = 2; }
};
void fb(B b) {
std::cout << b.b << std::endl;
}
int main(void) {
A a = genA();
B b(a);
fa(b); // => 1
fb(b); // => 2
}