[英]Python: How to extend a class?
So, I really want to add on a few new methods to pandas.core.frame.DataFrame
s. 因此,我真的很想为
pandas.core.frame.DataFrame
添加一些新方法。 For example, I want a method called .idx
: 例如,我想要一个名为
.idx
的方法:
pandas.core.frame.DataFrame.idx(self, rows, cols):
return self.iloc[rows].loc[cols]
Is this possible? 这可能吗? I'm not sure what the syntax should be - the class already exists from a library, so I can't just put the function inside the class definition.
我不确定语法应该是什么-该类已经存在于库中,所以我不能只是将函数放在类定义中。
Could you not extend your DataFrame
, inheriting all of its functions, and having the freedom to then define your own, on top? 您是否可以扩展
DataFrame
,继承其所有功能,然后自由地在顶部定义自己的数据DataFrame
?
In python it would look something like: 在python中,它看起来像:
class ExtendedDataFrame(DataFrame):
...
Then, simply use an instance of ExtendedDataFrame
, instead of DataFrame
, for your extra goodies. 然后,只需使用
ExtendedDataFrame
实例而不是DataFrame
来获得额外的好处。
I also suggest taking a look at this tutorial covering inheritance. 我还建议您阅读本教程 , 该教程涵盖了继承。
Also be sure to check out your version of python's implementation of super()
, if you're trying to override functions of the super (parent) class. 如果要覆盖super(父)类的功能,还请确保签出python实现的
super()
版本。
Here is a SO question with great information regarding super()
, because I'm noticing the tutorial I linked only briefly covers super()
, and in the comments no less. 这是一个有关
super()
重要信息的SO问题,因为我注意到链接的教程仅简要介绍了super()
,并且在注释中也不少。
This is actually really easy in Python. 在Python中,这实际上非常容易。 While I would recommend inheriting from DataFrame, as MeetTitan answered, sometimes that won't work, but you can just add on functions like this:
尽管我建议从DataFrame继承,正如MeetTitan回答的那样,有时候这是行不通的,但是您可以添加如下功能:
class Abc(object):
pass
def new_funct(self):
print 1234
Abc.instance_funct = new_funct
a = Abc()
a.instance_funct()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.