0

I am given a designated factory of A-type objects. I would like to make a new version of A-type objects that also have the methods in a Mixin class. For reasons that are too long to explain here, I can't use class A(Mixin), I have to use the A_factory. Below I try to give a bare bones example.

I thought naively that it would be sufficient to inherit from Mixin to endow A-type objects with the mixin methods, but the attempts below don't work:

class A: pass

class A_factory:
    def __new__(self):
        return A()
        
class Mixin:
    def method(self):
        print('aha!')

class A_v2(Mixin):  # attempt 1
    def __new__(cls):
        return A_factory()

class A_v3(Mixin):  # attempt 2
    def __new__(cls):
        self = A_factory()
        super().__init__(self)
        return self

In fact A_v2().method() and A_v3().method() raises AttributeError: 'A' object has no attribute 'method'.

What is the correct way of using A_factory within class A_vn(Mixin) so that A-type objects created by the factory inherit the mixin methods?

Ziofil
  • 1,815
  • 1
  • 20
  • 30
  • Why not `class A(Mixin)`? Why do you need `A_factory`? – mkrieger1 Dec 02 '21 at 13:09
  • I need to use `A_factory` because it contains a lot of logic for creating and initializing the appropriate `A` (`A`-type objects don't have a simple initialization). I just need to add some functionality to those objects. – Ziofil Dec 02 '21 at 13:10

1 Answers1

0

There's no obvious reason why you should need __new__ for what you're showing here. There's a nice discussion here on the subject: Why is __init__() always called after __new__()?

If you try the below it should work:

class Mixin:
    def method(self):
        print('aha!')

class A(Mixin):
    def __init__(self):
        super().__init__()

test = A()
test.method()

If you need to use a factory method, it should be a function rather than a class. There's a very good discussion of how to use factory methods here: https://realpython.com/factory-method-python/

defladamouse
  • 567
  • 2
  • 13
  • Thank you, but this is not what I am asking. What I am asking is: if I have to use a given factory of objects, how do I extend their functionality? – Ziofil Dec 02 '21 at 13:37
  • 1
    @Ziofil Can you edit your question to better explain the problem? – defladamouse Dec 02 '21 at 13:42