简体   繁体   中英

If I extend a class in python, how to automatically return the result as the new class?

Here is a simple example:

import pandas as pd

class test_pd(pd.DataFrame):

    def __init__(self):
        super().__init__()


    def my_copy(self):
        return self.copy()



if __name__=='__main__':
    a = test_pd() #a has a.my_copy()
    b = a.my_copy() #b does not have b.my_copy()

I would like the test_pd.my_copy() function to return a test_pd class whenever I called copy() function which is from pandas. Technically, I can always use something like return test_pd(self.copy()) . But I hope there could be a smarter solution so I don't have to make this modification every time I want to call a similar pandas function.

PS: I understand that DataFrame.copy() returns a DataFrame object, but I am just wondering, since my own class extends the DataFrame class, whether it is possible my object also extends a DataFrame Object automatically, so whenever the DataFrame function returns a DataFrame object, it will return a test_pd object when called in test_pd class.

You can access the class instance, and then use the cls function as a constructor, so:

def my_copy(self):
    return selfself.copy()

So here type(self) will be test_pd , but if you further subclass it, type(self) will be a sub_test_pd , and thus you will call that constructor.

Of course in case you change the __init__ at some level, you will have to update your my_copy as well, since then the parameters will no longer fit.

Note that for the above reason, and other reasons, this tends to be an anti-pattern. Yes it is technically possible, and yes, it can be beneficial. But it sometimes can fail quite dramatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM