Python嵌套类定义会导致无休止的递归。。。我做错什么了?

2024-09-30 06:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个程序,它可以打开输入文件,进行一些简单的文本解析,并输出结果。输入是一个ASCII文件,包含几个格式类似的文本块。所以,我想我应该利用这个机会来掌握如何定义自己的类。你知道吗

我有一个父类pFrame,我想继承pandas.DataFrame类的属性。因为我的输入文本文件包含两种类似(但不完全相同)的列型文本,所以我定义了另外两个类(pFrameApFrameB),每个类都继承父类。目前子类只是初始化一些变量;稍后我可以根据需要为一个、另一个或两个类定义简单的helper方法。你知道吗

下面是我为定义这些类而编写的模块的精简版本:

import pandas as pd

class pFrame(pd.DataFrame):
    pass

class pFrameA(pFrame):
    def __init__(self):
        self.units = ('msec', 'psi')
        self.numFormat = (int, float)
        self._gcHeaderStr = "          Time          Cell"


class pFrameB(pFrame):
    def __init__(self):
        self.units = ('in', 'in')
        self.numFormat  = (float, float)
        self._gcHeaderStr = "Disp 1        Disp 2"        

但当我尝试测试这些类定义时,Python会进入一个无休止的递归循环:

>>> import pFrameModule
>>> p=pFrameModule.pFrameA()

...
...
    if name in self.columns:
  File "properties.pyx", line 55, in pandas.lib.AxisProperty.__get__ (pandas/lib.c:29248)
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 2085, in __getattr__
    if name in self.columns:
  File "properties.pyx", line 55, in pandas.lib.AxisProperty.__get__ (pandas/lib.c:29248)
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 2085, in __getattr__
    if name in self.columns:
  File "properties.pyx", line 55, in pandas.lib.AxisProperty.__get__ (pandas/lib.c:29248)
RuntimeError: maximum recursion depth exceeded

有人能给我一个快速的指针来理解我遗漏了什么吗?你知道吗


Tags: columnsnamein文本selfpandasif定义
1条回答
网友
1楼 · 发布于 2024-09-30 06:31:11

将代码修改为以下内容似乎可以解决此问题:

import pandas as pd

class pFrame(pd.DataFrame):
    def __init__(self):
        super(pFrame, self).__init__()

class pFrameA(pFrame):
    def __init__(self):
        super(pFrameA, self).__init__()
        self.units = ('msec', 'psi')
        self.numFormat = (int, float)
        self._gcHeaderStr = "          Time          Cell"


class pFrameB(pFrame):
    def __init__(self):
        super(pFrameB, self).__init__()
        self.units = ('in', 'in')
        self.numFormat  = (float, float)
        self._gcHeaderStr = "Disp 1        Disp 2"     


p = pFrameA()
print p._gcHeaderStr    # To prove something is happening

{我并没有在初始化类的每一帧的时候,通过忽略它来怀疑它。你知道吗

相关问题 更多 >

    热门问题