调用一个函数重新实例化该类

时间:2019-08-28 02:24:23

标签: python-3.x

当我调用此函数

self.myplot = self.plot(x ='X', y ='Y', kind ='scatter')    

继承自pandas.DataFrame的类,而不是执行该函数,而是重新实例化该类,从而创建无限的递归实例。

import pandas as pd

class ChildDataFrame(pd.DataFrame):
    myplot = None

    @property
    def _constructor(self):
        return ChildDataFrame


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self['X'] = [2,3]
        self['Y'] = [3,4]

        print('Dataframe: \n',self)
        self.myplot = self.plot(x ='X', y ='Y', kind ='scatter')    

a=ChildDataFrame()

我应该如何调用该函数,以及为什么要重新实例化该类?

如果我将plot()调用移到类之外,它还会多次实例化该类

import pandas as pd

class ChildDataFrame(pd.DataFrame):
    myplot = None

    @property
    def _constructor(self):
        return ChildDataFrame


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self['X'] = [2,3]
        self['Y'] = [3,4]

        print('Dataframe: \n',self)

a=ChildDataFrame()
a.plot(x ='X', y ='Y', kind ='scatter') 

提供以下输出:

Dataframe:
    X  Y
0  2  3
1  3  4
Dataframe:
    X  Y
0  2  3
1  3  4
Dataframe:
    X  Y
0  2  3
1  3  4

1 个答案:

答案 0 :(得分:0)

请看下面的描述,希望对您有所帮助,您可以参考this link

class Base(object):
    def method(self):
        print 'original', type(self), self.__class__

class Derived(Base):
    def method(self):
        print 'derived', type(self), self.__class__
        super(type(self), self).method()
        # super(self.__class__, self).method()

class Subclass(Derived):
    def method(self):
        print 'subclass of derived', type(self), self.__class__
        super(Subclass, self).method()

调用Derived()。method()时,结果为

derived <class '__main__.Derived'> <class '__main__.Derived'>
original <class '__main__.Derived'> <class '__main__.Derived'>

这里,两个快捷方式均已正确评估。但是,当您调用Subclass()。method()时,结果将变为

subclass of derived <class '__main__.Subclass'> <class '__main__.Subclass'>
derived <class '__main__.Subclass'> <class '__main__.Subclass'>
derived <class '__main__.Subclass'> <class '__main__.Subclass'>
derived <class '__main__.Subclass'> <class '__main__.Subclass'>
... skip ...
RuntimeError: maximum recursion depth exceeded while calling a Python object

在该示例中,调用super(Subclass)可以正常工作,并按预期方式调用Derived.method()。然后我们在Derived.method()内部调用super(Subclass),这将导致我们回到递归循环的位置。仅当您有其他类继承自使用错误调用的类

时,此问题才可见