【发布时间】:2019-11-16 14:38:49
【问题描述】:
我有一个处理数组的类,并根据类型用不同的类包装它或制作一个生成器
外套类决定如何处理参数
涂层是核心类
class Coat:
def __new__(cls, array, dtype=np.float32):
if isinstance(array, np.ndarray):
print('Condition 1')
template = dtype(Coating(array.shape) * 0 + array)
return template
if isinstance(array, (list,tuple, GeneratorType)):
print('Condition 2')
for item in array:
yield dtype(Coating(item.shape) * 0 + item)
class Coating(np.ndarray):
def __init__(self, *args, **kwargs):
if len(self.shape) < 2:
raise Exception("Not accustomed for 1D")
def ...
...
所以当我尝试触发两个条件(条件 1 或条件 2)时
iterable = Coat([np.zeros(shape = [20,35]),np.zeros(shape = [20,35]),np.zeros(shape = [20,35])])
print(iterable)
array = Coat(np.zeros(shape=[10,10]),dtype=np.uint8)
print(array)
它返回给我生成器:
<generator object Coat.__new__ at 0x7fc2b4410bf8>
<generator object Coat.__new__ at 0x7fc291b5ef10>
新中没有打印任何内容。
但是,如果我删除生成器创建,一切正常
class Coat:
def __new__(cls, array, dtype=np.float32):
if isinstance(array, np.ndarray):
print('Condition 1')
template = dtype(Coating(array.shape) * 0 + array)
return template
if isinstance(array, (list,tuple, GeneratorType)):
print('Condition 2')
然后
Condition 2
None
Condition 1
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
__new__ 中的 yield 怎么可能表现得如此占主导地位,也就是说,即使它在未触发的条件中也会造成混乱?
【问题讨论】:
-
我不认为 new 是适合这项工作的工具
-
目前还不清楚您为什么会有其他预期。在任何分支上产生的任何函数都会返回一个生成器。
-
@D.BenKnoble 那么什么是好的做法呢?
-
看起来您只是在两个不同的结果之间做出选择——一个函数? new 通常用于元编程。函数也可以返回类和对象
-
__new__不一定用于元编程,但是当Coat的__new__方法从不返回Coat的实例时,它几乎没有理由成为一个类;它也可能是一个普通的功能。 (请特别注意,您永远不会在正文中使用cls的值,这肯定表明您正在做一些不必要的复杂事情。)
标签: python class oop metaprogramming yield