我想创建一个继承自 pandas.Series 的新类。我通常在 python 中创建子类没有任何问题,但在这种情况下我遇到了问题。
这是一个简单的继承方案:
class Test(object):
def __new__(cls, *args, **kwargs):
print "new Test"
return object.__new__(cls, *args, **kwargs)
def __init__(self):
print "init Test"
class A(Test):
def __new__(cls, *args, **kwargs):
print "new A"
return Test.__new__(cls, *args, **kwargs)
def __init__(self):
print "init A"
print "creating an instance of A"
a = A()
print "type: ", type(a)
输出:
creating an instance of A
new A
new Test
init A
type: <class '__main__.A'>
现在让我们尝试一个系列:
import pandas as pd
class subSeries(pd.Series):
def __new__(cls, *args, **kwargs):
print "new subSeries"
return pd.Series.__new__(cls, *args, **kwargs)
def __init__(self):
print "init subSeries"
print "creating an instance of subSeries"
s = subSeries()
print "type: ", type(s)
我们得到:
creating an instance of subSeries
new subSeries
type: <class 'pandas.core.series.Series'>
为什么是s
系列而不是子系列?