运行此代码:
import weakref
class A(object):
_instances = []
def __init__(self):
self._instances.append(weakref.ref(self))
@property
@classmethod
def instances(cls):
for inst_ref in cls._instances:
inst = inst_ref()
if inst is not None:
yield inst
foo = A()
bar = A()
for inst in A.instances:
print inst
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
Traceback (most recent call last):
File "test.py", line 18, in <module>
for inst in A.instances:
TypeError: 'property' object is not iterable
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚类方法的行为如何像属性(没有括号).
我尝试记录一个:rtype:docstring参数,返回一个生成器Node:
def __iter__(self):
"""iterate over node children
:rtype: ???
"""
for node in self.children.itervalues():
yield node
Run Code Online (Sandbox Code Playgroud)
什么:rtype:是应该是什么?generator of Node似乎不起作用.
在字符串中格式化dict键的正确方法是什么?
当我这样做:
>>> foo = {'one key': 'one value', 'second key': 'second value'}
>>> "In the middle of a string: {foo.keys()}".format(**locals())
Run Code Online (Sandbox Code Playgroud)
我期待的是:
"In the middle of a string: ['one key', 'second key']"
Run Code Online (Sandbox Code Playgroud)
我得到了什么:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
"In the middle of a string: {foo.keys()}".format(**locals())
AttributeError: 'dict' object has no attribute 'keys()'
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的,我的dict有键:
>>> foo.keys()
['second key', 'one key']
Run Code Online (Sandbox Code Playgroud) 我有这个代码:
// my.h
#ifndef MY_HEADER
#define MY_HEADER
int create_uid();
#endif
Run Code Online (Sandbox Code Playgroud)
// my.cpp
#include "my.h"
static int _next_uid = 0;
int create_uid()
{
return _next_uid++;
}
Run Code Online (Sandbox Code Playgroud)
我想内联create_uid(),同时保持_next_uid变量对程序全局,以便变量是唯一的。
我的问题是:
inlinerequire 语句_next_uid在编译单元之外是否可见?注意:这似乎并没有清楚地回答这些问题。
use std::mem::size_of;
struct Position {
x: f32,
y: f32,
z: f32,
}
struct PoolItem {
entity_id: u32, // 4 bytes
used: bool, // 1 bytes + 3 (padding)
component: Position, // 12 bytes
}
assert_eq!(size_of::<u32>(), 4);
assert_eq!(size_of::<Position>(), 12);
assert_eq!(size_of::<PoolItem>(), 20);
Run Code Online (Sandbox Code Playgroud)
如您所见,这样的结构有 20 个字节长。Position实际上是可选的并且取决于used.
使用会Option消除对used字段的需求并将结构大小减少到 16 个吗?
struct PoolItem {
entity_id: u32, // 4 bytes
component: Option<Position>, // 12 bytes ?
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,如何Option实现这种行为?
我在Playground 上的测试似乎表明它不起作用。为什么?