我正在尝试使用ndarray库在 Rust 中实现康威生命游戏的一次迭代。
我认为循环数组的 3x3 窗口将是一种计算活着的邻居的简单方法,但是我在进行实际更新时遇到了麻烦。
该数组表示有生命#和没有生命:
let mut world = Array2::<String>::from_elem((10, 10), " ".to_string());
for mut window in world.windows((3, 3)) {
let count_all = window.fold(0, |count, cell| if cell == "#" { count + 1 } else { count });
let count_neighbours = count_all - if window[(1, 1)] == "#" { 1 } else { 0 };
match count_neighbours {
0 | 1 => window[(1, 1)] = " ".to_string(), // Under-population
2 …Run Code Online (Sandbox Code Playgroud) 我想要实现的是这样的:
class object:
def __init__(self):
WidthVariable(self)
print self.width
#Imagine I did this 60frames/1second later
print self.width
#output:
>>0
>>25
Run Code Online (Sandbox Code Playgroud)
我想要发生的事情(如上所述):WidthVariable创建类时,它将变量添加width到对象实例。该变量的行为类似于常规属性,但是在这种特殊情况下,它是只读的(仅fget设置了变量)。另外,fget调用定义的函数WidthVariable决定width返回什么。
但是,我不知道该怎么做!我使用常规属性进行了尝试,但发现它们仅适用于类,而不适用于每个实例-请注意,我使用的代码应与上述代码尽可能相似(即,__init__of中的代码WidthVariable应设置width变量,而无其他地方) 。而且,self.width不能成为函数,因为我没有self.width()想要的名字self.width(因为它与我拥有的其余设计保持一致)。
需要说明的是,完整的代码如下所示:
class MyObject:
def __init__(self)
WidthVariable(self)
print self.width
class WidthVariable:
def __init__(self, object)
object.width = property(self.get_width)
def get_width(self):
value = #do_stuff
return value #The Value
#output:
>>25 #Whatever the Value was
Run Code Online (Sandbox Code Playgroud)