如何在Python中为现有类添加方法? [英] How to add method to existing class in Python?

查看:336
本文介绍了如何在Python中为现有类添加方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有要添加到pandas的非常方便的高级pd.DataFrame保存功能.如何将此方法添加到pd.DataFrame类?

I have this really convenient high-level pd.DataFrame saving function that I want to add to pandas. How can I add this method to the pd.DataFrame class?

def to_file(df, path, sep="\t", compression="infer", pickled="infer", verbose=False, **args):
    _ , ext = os.path.splitext(path)
    # Serialization
    if pickled == "infer":
        if ext in {".pkl", ".pgz", ".pbz2"}:
            pickled = True
        else:
            pickled = False
    # Compression
    if compression == "infer":
        if pickled:
            if ext == ".pkl":
                compression = None
            if ext == ".pgz":
                compression = "gzip"
            if ext == ".pbz2":
                compression = "bz2"
        else:
            compression = None
            if path.endswith(".gz"):
                compression = "gzip"
            if path.endswith(".bz2"):
                compression = "bz2"
    if verbose:
        print(
            f"path:\t{path}", 
            f"sep:\t{repr(sep)}",
            f"compression:\t{compression}",
            f"pickled:\t{pickled}", 
            sep="\n", 
            file=sys.stderr,
        )
    if pickled == False:
        df.to_csv(path, sep=sep, compression=compression, **args)
    if pickled == True:
        df.to_pickle(path, compression=compression, **args)

推荐答案

使用python类继承.这样一来,您就可以使用Pandas数据框中的所有方法,并且仍然可以定义自己的方法.

Use python class inheritance. This will allow you to use all the methods in a Pandas data frame and still define your own methods.

import pandas as pd

class NewDF(pd.DataFrame)
    def __init__(self, *args):
        pd.DataFrame.__init__(self, *args)

    def to_file(df, path, sep="\t", compression="infer", pickled="infer", verbose=False, **args):
        ...

这篇关于如何在Python中为现有类添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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