简体   繁体   中英

Python - inherited class method to operate on class attribute

I'm sure there's probably a simple solution but anyway the problem is this: I've got two classes, say A and B , both of which have attributes that are dataframe like -- those attributes are instances of a dataframe class, call it C , which has its own methods. I'd like to define an 'interface like' class D which has methods that can operate on those attributes (ie operate on the dataframes which are attributes of A and B ).

edit for clarity : in what follows below, let a and b be dataframes (ie instances) from class C . So that the methods of C are available to a and b .

To be more explicit: Suppose a is the dataframe like attribute of A , with attributes Series1 ,..., Seriesn . Since a is dataframe like, I can call a.Series1, a.Series2, ... etc to access the contents of Series1 , Series2 in a . Of course a is an attribute of A so I'm actually calling AaSeries1 , AaSeries2 .. etc, and a has its own methods from class C so I can call AaSeries1.methodfromclassC() no problem. Anyhow. Now suppose I want to make a transformation in a consistent fashion to the contents of a.Seriesj , or b.Seriesj , implemented as a method in class D , that both A and B can access. The idea being that I'd like to be able to call a member of class A like so: AaSeriesj.transformseries() . The problem I run into is that Seriesj has its own methods (inherited from class C ) and transformseries() is not one of them.

This probably seems a bit convoluted but the idea being that eventually I can chain multiple calls to the various methods of D changing the state of the dataframe attributes: AaSeries2.transform1().transform2().transformj() or BbSeriesj.transform6().transform3() etc, so that the final representation of Aa and Bb is in the form that I'd like.

Have you considered "injecting" new methods to your Seriesn ? In Python you can add methods to classes dynamically like this:

setattr(MyClass, 'new_method', lambda self: 'return value')

It will work even in objects instanced before. So you could add custom methods to Pandas' Series and/or Dataframe classes.

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