Milad
Milad

Reputation: 5510

How to create new subclasses by adding the same method to multiple classes

I have 5 classes that are all subclasses of a parent class. I want to define new subclasses for each of these classes by adding an identical method to each of them. Is there a way to do this dynamically? Does this have a name in OOP terminology?

In below new_method is exactly the same for all cases so I'd prefer to repeat myself.

class A(MySuperClass)
class B(MySuperClass)
class C(MySuperClass)
class D(MySuperClass)

class AAA(A):

    def new_method():
        ...

class BBB(B):

    def new_method():
        ...

class CCC(C):

    def new_method():
        ...

class DDD(D):

    def new_method():
        ...

Upvotes: 1

Views: 692

Answers (3)

r.ook
r.ook

Reputation: 13868

Besides multiple inheritance, you can also use a decorator if it is more convenient to your code:

def add_new_method(cls):
    def new_method(self, ...):
        pass
    cls.new_method = new_method
    return cls

@add_new_method
class AAA(A):
    ...

However, if you don't necessarily need a new AAA subclass, but just wanted to add new_method to A, B, C, D from the superclass, then it's as easy as:

def new_method(self, ...):
    pass

A.new_method = new_method

Even better yet. If MySuperClass can be changed, you can simply do:

MySuperClass.new_method = new_method

# A, B, C and D will all have new_method automatically.

Upvotes: 2

Rocky Li
Rocky Li

Reputation: 5958

You can use type to dynamically create classes:

class Foo(object):
    def __init__(self):
        print("NOTHING")

def func(self):
    print("ARRRGH")

Bar = type('Bar', (Foo,), {"func": func})
Bar2 = type('Bar2', (Foo,), {"func": func})
Bar3 = ... # Put in loop if you like.

b = Bar() # This will print "NOTHING", Bar2, Bar3 works the same way.
b.func() # will print "ARRRGH"

Upvotes: 0

adnanmuttaleb
adnanmuttaleb

Reputation: 3614

You can solve repetition by creating new class that contains your new_method as follows:

class A(MySuperClass)
class B(MySuperClass)
class C(MySuperClass)
class D(MySuperClass)

class Mixin():
    def new_method():
        pass

class AAA(A, Mixin):
    pass

This is called multi-inheritance. you can consider here inheritance as both specialization mechanism and also code sharing.

Upvotes: 4

Related Questions