小编luo*_*o23的帖子

元类和 __prepare__ ()

我正在自学这个__prepare__功能。我在PEP3115看到了这个片段

# The custom dictionary
class member_table(dict):
    def __init__(self):
        self.member_names = []

    def __setitem__(self, key, value):
        # if the key is not already defined, add to the
        # list of keys.
        if key not in self:
            self.member_names.append(key)

        # Call superclass
        dict.__setitem__(self, key, value)

# The metaclass
class OrderedClass(type):

    # The prepare function
    @classmethod
    def __prepare__(metacls, name, bases): # No keywords in this case
        return member_table()

    # The metaclass invocation
    def __new__(cls, name, bases, classdict):
        # Note …
Run Code Online (Sandbox Code Playgroud)

python metaclass

11
推荐指数
1
解决办法
3518
查看次数

如何在修改容器时正确迭代容器?

我想在迭代时修改我的容器。但是代码的第一个版本不能正常工作。有人可以解释原因吗?

// version 1
int main(){
    int a=1, b=2, c=5;
    std::set<int*> m = {&a, &b, &c};

    for(auto mi : m){
        std::cout << *mi << std::endl;
        m.erase(mi);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试了另一个版本。好像没问题。当我这样迭代时有什么潜在的问题吗?

// version 2
int main(){
    int a=1, b=2, c=5;
    std::set<int*> m = {&a, &b, &c};

    while (!m.empty()){
        std::cout << **m.begin() << std::endl;
        m.erase(m.begin());
    }

}
Run Code Online (Sandbox Code Playgroud)

c++ iterator loops

3
推荐指数
1
解决办法
210
查看次数

如何在Golang中按索引交换值

在 python 中numpy,可以像这样轻松地按列表中的索引交换值:

a[[2, 3, 5]] = a[[5, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

有没有什么好办法在Golang中实现这个功能。

swap go assign

0
推荐指数
1
解决办法
355
查看次数

标签 统计

assign ×1

c++ ×1

go ×1

iterator ×1

loops ×1

metaclass ×1

python ×1

swap ×1