vendredi 22 mai 2015

Python: Creating a new instance of itself from a base class (possibly via reflection?)

I have code that looks like the following and I'm trying to refactor it.

# Abstract, do not instantiate Base
class Base:
    ...


class A(Base):
    ...
    def func():
        x = A(1, 2, 3)
        x.x()
        y = A(4, 5, 6)
        y.y()
        z = A(7, 8, 9)
        z.z()

class B(Base):
    ...
    def func():
        x = B(1, 2, 3)
        x.x()
        y = B(4, 5, 6)
        y.y()
        z = B(7, 8, 9)
        z.z()


class C(Base):
    ...
    def func():
        x = C(1, 2, 3)
        x.x()
        y = C(4, 5, 6)
        y.y()
        z = C(7, 8, 9)
        z.z()

Due to the problem needing recursion to solve, the classes will recursively call themselves through func() (so A will make some A's that will make some more A's until the recursive function finishes), and the best way for me to refactor this is to dynamically create the class. If there was a way to get the final runtime class, I could refactor it to look like:

# Abstract, do not instantiate Base
class Base:
    ...
    def func():
        constructor = # Magic here to get the actual class type's constructor
        # I'm guessing reflection would do something like this...? I don't know.
        x = constructor.__init__(1, 2, 3) # If this is an A, make an A... if it's a B, make a B... etc
        x.x()
        y = constructor.__init__(4, 5, 6)
        y.y()
        z = constructor.__init__(7, 8, 9)
        z.z()

class A(Base):
    ...


class B(Base):
    ...


class C(Base):
    ...

I don't know much about Python and it's reflection capability, or if there's some other better way of doing this.

Can this be done?

Is there a better way than reflection?

Note: the constructor args are just arbitrary placeholders I made up.

Note 2: performance is irrelevant for this, I am just interested in if this is possible, and if so -- how?





Aucun commentaire:

Enregistrer un commentaire