我想要类似a dict的东西,class TestClass其中包含非默认参数。当我访问时,我不知道要问的元素是否早于此。因此TestClass:
class TestClass(object):
def __init__(self, name):
self.name = name
self.state = 0
def getName(self):
self.state = self.state + 1
return "%s -- %i" % (self.name, self.state)
Run Code Online (Sandbox Code Playgroud)
然后dict和访问函数:
db = {}
def getOutput(key):
# this is a marvel in the world of programming langauges
if key not in db:
db[key] = TestClass(key)
return db[key]
Run Code Online (Sandbox Code Playgroud)
以及实际的测试代码:
if __name__ == "__main__":
print "testing: %s" % getOutput('charlie').getName()
Run Code Online (Sandbox Code Playgroud)
真好 但是我想知道是否有更优雅的解决方案。浏览时,defaultdict进入了我的脑海。但这是行不通的,因为我无法将参数传递给default_factory:
from collections …Run Code Online (Sandbox Code Playgroud) 我尝试编写一个C++模板类,它应该能够通过相同的接口处理"简单"类型和类似"Eigen :: MatrixBase"的类型.我设法通过两种不同的简单类型获得所需的行为,但很难将Eigen语法压缩到我的最小例子中......也许有人可以给我一个建议?
环顾四周,这接近我想要的 - 没有Eigen.这看起来也很相似.
#ifndef __MINIMAL_H__
#define __MINIMAL_H__
#include <Eigen/Core>
// base-class defining and interface + common functions
// child-classes with possible overloads. does not work to
// define basic eigen-types as template specialization parameter
template<typename T>
class MinimalBase
{
public:
MinimalBase(const T& val)
:val(val){};
T val;
// pure virtual interface
virtual void setZero() = 0;
// the common functionality
void increase() { val = val*6; };
void decrease() { val = val/7; }; …Run Code Online (Sandbox Code Playgroud) c++ ×1
defaultdict ×1
dictionary ×1
eigen ×1
inheritance ×1
karma-runner ×1
python ×1
templates ×1