简体   繁体   中英

Python Classes: differences between inheritance and create a parent class instance inside the child (class composition)

I have the following problem:

I have a class A , that only stores a big numbers of variables; then I have 3 classes, B , C , D , that inherit A to define more complex objects (different in each of the 3 classes) that depend on the set of variables defined in A . Finally there is a class E that has to inherit only one between B , C , D .

Since I want the flexibility to choose each time the class to include in E I don't want a fixed Parent name as argument of E . To do so, instead of inherit the class I'm creating a class instance in the __init__() method (to access all the parent's methods and attributes as well); I report below the 2 different way to better express the idea. My question is:

Is there some cons in proceeding my way, or, more in general, which are the differences between the 2 approaches?

class E(D):
    def __init__(self, argsE, argsPar):
        super().__init__(self, argsPar)
    ...

(in the example above I have to specify the parent class, which I want to give in input and not to be fixed)

class E:
    def __init__(self, parent, argsE, argsPar):
        if(parent=='B')
            self.parent = B(argsPar)
        if(parent=='C')
            self.parent = C(argsPar) 
        if(parent=='D')
            self.parent = D(argsPar)
      
    ...

Since I want the flexibility to choose each time the class to include in E I don't want a fixed Parent name as argument of E .

Then just exploit type to dynamically create class, consider following example

class A:
    pass
class B:
    pass
choice = input("Shall C inherit A xor B?")
if choice == "A":
    C = type("C", (A,), {})
elif choice == "B":
    C = type("C", (B,), {})
else:
    exit()
print(issubclass(C,A))  # True if choice was A else False
print(issubclass(C,B))  # True if choice was B else False

Third argument to type should be

dictionary contains attribute and method definitions for the class body

In above example for brevity sake empty dict was used,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM