【发布时间】:2020-07-28 03:07:45
【问题描述】:
我想写一个继承map类的自定义类。
class mapT(map):
def __init__(self,iii):
self.obj = iii
但我无法初始化它。
# Example init object
ex = map(None,["","1","2"])
exp1 = mapT(ex)
# TypeError: map() must have at least two arguments.
exp1 = mapT(None,ex)
# TypeError: __init__() takes 2 positional arguments but 3 were given
如何在python中创建一个继承map的类? 或者为什么我不能在 python 中继承 map?
===== 添加=====
我想要实现的是为可迭代对象添加自定义方法
def iterZ(self_obj):
class iterC(type(self_obj)):
def __init__(self,self_obj):
super(iterC, self).__init__(self_obj)
self.obj = self_obj
def map(self,func):
return iterZ(list(map(func,self.obj))) # I want to remove "list" here, but I can't. Otherwise it cause TypeError
def filter(self,func):
return iterZ(list(filter(func,self.obj))) # I want to remove "list" here, but I can't. Otherwise it cause TypeError
def list(self):
return iterZ(list(self.obj))
def join(self,Jstr):
return Jstr.join(self)
return iterC(self_obj)
所以我可以这样做:
a = iterZ([1,3,5,7,9,100])
a.map(lambda x:x+65).filter(lambda x:x<=90).map(lambda x:chr(x)).join("")
# BDFHJ
而不是这个:
"".join(map(lambda x:chr(x),filter(lambda x:x<=90,map(lambda x:x+65,a))))
【问题讨论】:
-
这没有任何意义。
map在技术上是 CPython 中的一个类,但这不是一个书面保证,无论哪种方式,__init__对map子类没有意义。 -
无论你想要实现什么,子类化
map几乎肯定不是实现它的方法。 -
为什么你需要为这个映射子类???此外,停止在所有迭代器上使用
list,这违背了它们是迭代器的意义。无论如何,您可以继承地图,但由于上述原因,我不会。请注意,__new__可能会妨碍您的实现 -
再一次,为每个函数调用创建一个类并动态继承
class iterC(type(self_obj))有什么意义?为什么不只是一个不从任何东西(默认对象除外)继承的函数之外的类?即class iterC: ...? -
这是一个包装器的工作,而不是一个子类。无论如何,您没有使用原始对象的任何方法 - 地图迭代器拥有的唯一方法是您不太可能直接调用的东西。
标签: python python-3.x python-class