简体   繁体   English

在 python 中扩展 class 的正确方法

[英]correct way of extending a class in python

I am given a designated factory of A -type objects.我得到了一个A型对象的指定工厂。 I would like to make a new version of A -type objects that also have the methods in a Mixin class.我想制作一个新版本的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 .由于这里解释太长的原因,我不能使用class A(Mixin) ,我必须使用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:我天真地认为从Mixin继承来赋予A类型的对象以 mixin 方法就足够了,但是下面的尝试不起作用:

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' .事实上A_v2().method()A_v3().method()引发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?class A_vn(Mixin)中使用A_factory的正确方法是什么,以便工厂创建的A类型对象继承 mixin 方法?

There's no obvious reason why you should need __new__ for what you're showing here.没有明显的理由为什么你需要__new__来展示你在这里展示的东西。 There's a nice discussion here on the subject: Why is __init__() always called after __new__()?关于这个主题有一个很好的讨论: 为什么 __init__() 总是在 __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.如果您需要使用工厂方法,它应该是 function 而不是 class。 There's a very good discussion of how to use factory methods here: https://realpython.com/factory-method-python/这里有一个关于如何使用工厂方法的很好的讨论: https://realpython.com/factory-method-python/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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