【发布时间】:2017-01-13 08:03:29
【问题描述】:
在 python 库 pytides 中,我遇到了一种奇怪的方法来初始化一个类(Tide 类及其 initialization )。 我在下面转载了代码的简化版本:
import numpy as np
class Foo(object):
def __init__(self,x,y):
self.x = x
self.y = y
class Foobar(object):
dtype = np.dtype([('fooObj', object),
('A', float),
('B', float)])
def __init__(self,model):
'''model: an ndarray of type Foobar.dtype '''
self.model = model
# initialize a Foobar object
myFoos = [Foo(4,3),Foo(4,9),Foo(0,2)]
A = [2,3,4]
B = [8,9,0]
model = np.zeros(len(myFoos), dtype = Foobar.dtype)
model['fooObj'] = myFoos #what is that?!?
model['A'] = A
model['B'] = B
myFoobar = Foobar(model=model)
据我了解,Foobar 中的 dtype 变量是一个全局变量,但我不明白拥有它有什么意义。只是在这里提供一种方便的方式来初始化 Foobar 吗?而且 Foobar 类在构造时需要一个 Foobar.dtype 数组,是不是一种循环调用(应该崩溃)?
【问题讨论】:
-
Foobar中的dtype变量不是全局变量,它是一个类属性,由Foobar类的所有实例共享。跨度>
标签: python python-3.x oop numpy