Mar-16-2021, 08:10 PM
Hi,
My current project implementation provides a base class and a child class which provides variables for the base class to use in its methods. For example:
My project generates custom child classes with unique names that are based on a dataset. The child classes are always inheriting the same base class. The child classes kinda act as containers for unique data, and the base class basically provides different ways to access that child class info.
I'd like to expand my project to provide a subclassable BaseClass to provide a different implementation for specific methods in the BaseClass. For example:
The above works fine, but my problem is I'd like the CustomClass in the example to be user-defined. So I won't be able to predict what class name they use. If I can't predict the classname, then my Child class generator cannot provide the correct Base Class to inherit.
My idea is to use the __subclasses__ variable to check if base class has any subclasses, and pass that conditionally to the Child class:
Seems a bit hacky to me, so was wondering if there is some better implementation of what I'm trying to do. Another problem I haven't really thought about is that the CustomClass that the user defines will probably live in a different file, so figuring out the importing might be tricky as well...
Thanks!
My current project implementation provides a base class and a child class which provides variables for the base class to use in its methods. For example:
1 2 3 4 5 6 7 8 9 10 11 |
class BaseClass( object ): def print_name( self ): print ( self .name) class Person1(BaseClass): name = "Bob" bob_inst = Person1() bob_inst.print_name() |
I'd like to expand my project to provide a subclassable BaseClass to provide a different implementation for specific methods in the BaseClass. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class BaseClass( object ): def print_name( self ): print ( self .name) class CustomClass(BaseClass): def print_name( self ): print ( "Hello my name is %s" % self .name) class Person1(CustomClass): name = "Bob" bob_inst = Person1() bob_inst.print_name() |
My idea is to use the __subclasses__ variable to check if base class has any subclasses, and pass that conditionally to the Child class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class BaseClass( object ): def print_name( self ): print ( self .name) class CustomClass(BaseClass): def print_name( self ): print ( "Hello my name is %s" % self .name) if ( len (BaseClass.__subclasses__()) > 0 ): inherited_name = BaseClass.__subclasses__()[ 0 ] else : inherited_name = BaseClass class Person1(inherited_name): name = "Bob" bob_inst = Person1() bob_inst.print_name() |
Thanks!