Python:我如何对嵌套类进行子类化?

2 投票
3 回答
884 浏览
提问于 2025-04-15 23:02

我正在尝试在一段Python代码中做以下事情:

class Parent:
    class Child(Parent):
        pass

但是它没有成功。有没有什么Python的写法可以让我达到同样的效果呢?

谢谢。

3 个回答

0

我强烈建议不要做下面这样的事情;我想不出有什么理由去这样做,而且这太复杂了。不过为了学习的目的……

其实可以通过元类(或者说类装饰器)在父类创建后,把某个来自类定义的对象替换成一个真正的子类。

举个例子,在下面的代码中,我们检查每个类属性的 __bases__ 属性里是否有一个特殊的标记(一个叫 ReplaceMe 的类)。如果找到了这个标记,我们就认为它是一个应该被替换成子类的占位符。然后我们动态创建一个新的(子)类,把 ReplaceMe 替换成我们自己。

class ReplaceMe(object): pass

class DerivedInnerChildren(type):
    def __init__(cls, name, bases, attrs):
        for k, v in attrs.items():
            if ReplaceMe in getattr(v, '__bases__', ()):
                child_name = v.__name__
                child_bases = tuple([
                    base if base is not ReplaceMe else cls
                    for base in v.__bases__])
                child_attrs = dict(v.__dict__)
                setattr(cls, k, type(child_name, child_bases, child_attrs))

class Parent(object):
    __metaclass__ = DerivedInnerChildren
    class Child(ReplaceMe): 
        pass

print Parent
print Parent.Child
print 'Parent in Child mro?', Parent in Parent.Child.__mro__
print Parent.Child.__mro__

这段代码的输出是:

<class '__main__.Parent'>
<class '__main__.Child'>
Parent in Child mro? True
(<class '__main__.Child'>, <class '__main__.Parent'>, <type 'object'>)
1

在Python中,内部类和外部类之间没有特别的关系,所以其实没必要使用内部类。而且,把一个类作为另一个类的属性通常也不是最好的设计。如果稍微调整一下结构,我相信你可以找到一个不需要这种做法的解决方案,而且会更好、更符合常规写法。

4

你不能这样做,因为在定义Child的时候,Parent还没有被定义(还在定义中)。在Python中,嵌套类通常不太常用,你可以在同一个模块里直接声明不同的类。不过,如果你真的需要实现这种结构,你可以这样做:

class Parent: pass
class Child (Parent): pass

Parent.Child = Child
del Child

撰写回答