从现有的类中构建一个类 [英] building a class from an existing one

查看:137
本文介绍了从现有的类中构建一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从pandas DataFrame构建一个类。我只想在DataFrame类中添加一个属性name。但是下面的代码会产生递归最大深度误差。哪种方式可以使它工作?谢谢

I am trying to build a class from pandas DataFrame. I just want to add an attribute 'name' to DataFrame class. But the codes below yield errors in recursion maximum depth reached. Which way to make it work? Thanks

import pandas as pd
class DatFrame(pd.DataFrame):
    def __init__(self, name, data=None, index=None, columns=None,
                 dtype=None, copy=False):
        self.name = name
        pd.DataFrame.__init__(self, data=None, index=None, 
                              columns=None, dtype=None, copy=False)


x = array([[9, 7, 5],
          [7, 3, 1],
          [8, 8, 3],
          [7, 4, 3]])
cols = ['a', 'b', 'c']
index = ['D', 'E', 'F', 'G']

s = DatFrame('huy', x, index, cols)

错误:RecursionError:调用Python对象时超出了最大递归深度

Error: RecursionError: maximum recursion depth exceeded while calling a Python object

推荐答案

首先,您将传递给数据帧的所有参数

First, you're passing None to all parameters of your dataframe

其次,修复是在设置 name __ init __ 方法c $ c>。

Second, the fix it is to call the __init__ method first, before setting name.

这可能是因为 pd.DataFrame 对象在初始化时需要一个空变量字典(递归)发生在 __ getattr __ )中,而您的名称成员会混淆它:

It's probably because the pd.DataFrame object expects an empty variable dictionary when initializing (recursion occurs in __getattr__), and your name member confuses it:

class DatFrame(pd.DataFrame):
    def __init__(self, name, data=None, index=None, columns=None,
                 dtype=None, copy=False):
        pd.DataFrame.__init__(self, data=data, index=index,
                              columns=columns, dtype=dtype, copy=copy)
        self.name = name

作为一般规则,首先调用父构造函数总是更好,然后设置你的具体细节。

As a general rule, it's always better to call the parent constructor first thing, then set your specifics.

正如评论所说,如果它只是添加 name (不添加方法)你可以创建一个动态添加属性的工厂方法,不需要继承:

As comments said, if it's only to add name (without adding methods) you could create a factory method that adds dynamically the attribute, no need to inherit:

def create_datframe(name,*args,**kwargs):
    r = pd.DataFrame(*args,**kwargs)
    r.name = name
    return r

这篇关于从现有的类中构建一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆