Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在类构造过程中正确实现方法继承_Python_Inheritance_Super_Metaclass - Fatal编程技术网

Python 在类构造过程中正确实现方法继承

Python 在类构造过程中正确实现方法继承,python,inheritance,super,metaclass,Python,Inheritance,Super,Metaclass,如何在类完全构造之前调用的方法中实现超级类行为。我可以实现这样一系列相互依赖的方法吗 from six import with_metaclass class Meta(type): """a metaclass""" def __init__(cls, name, bases, classdict): cls.setup_class() def setup_class(cls): pass class A(with_metacl

如何在类完全构造之前调用的方法中实现超级类行为。我可以实现这样一系列相互依赖的方法吗

from six import with_metaclass

class Meta(type):
    """a metaclass"""

    def __init__(cls, name, bases, classdict):
        cls.setup_class()

    def setup_class(cls):
        pass


class A(with_metaclass(Meta, object)):
    """a class"""

    @classmethod
    def instantiate(cls, name):
        print("instantiating through '%s'" % name)

    @classmethod
    def setup_class(cls):
        cls.instantiate('A')


class B(A):

    @classmethod
    def setup_class(cls):
        super(B, cls).setup_class()
        cls.instantiate('B')

class C(B) pass
显然,这是行不通的,因为调用
setup\u class
时,
B
并不正确存在


我有一段时间都在问这个问题,但找不到一篇解释元类这一方面的文章。事实上,我拥有它的时间太长了,所以我想出了这个替代品,而且最终是不必要的。从技术上讲,它完全符合我想要的语法(这很酷),但最终它是一个黑客。由于我花了这么长时间编写了一段毫无意义(但仍然很酷)的代码,我想我至少应该试着确保没有其他人陷入同样的困境

我的困惑实际上源于这样一个事实,即我没有完全扩展我对元类的理解,以及元类与类之间的关系,从而得出它的逻辑结论。因此,事实证明,创建我想要的继承类型的最佳方法实际上是在一系列元类中执行它-出于同样的原因,试图通过类的实例继承属性没有意义,使元类的实例多态也没有意义:

from six import with_metaclass

class Meta(type):
    """a metaclass"""

    def __init__(cls, name, bases, classdict):
        print("Beginning '%s' setup" % name)
        cls.setup_class()
        print("Finished '%s' setup \n" % name)

    def setup_class(cls):
        cls.attribute = 0
        cls.instantiate('Meta')


class AMeta(Meta):

    def setup_class(cls):
        super(AMeta, cls).setup_class()
        cls.instantiate('A')

    def instantiate(cls, name):
        print("instantiating through '%s'" % name)

class A(with_metaclass(AMeta, object)): pass


class BMeta(AMeta):

    def setup_class(cls):
        super(BMeta, cls).setup_class()
        cls.instantiate('B')

class B(with_metaclass(BMeta, object)): pass


class C(B): pass
如果有人想更彻底地研究一下,我相信有人会很感激的