首页 \ 问答 \ 将字典中的值分配给对象(Assigning values from dictionary to object)

将字典中的值分配给对象(Assigning values from dictionary to object)

我经常需要做这样的事情:

"Some dictionary with values obtained somehow (e.g. submitted form values)"
my_dict = {
    'name': 'John',
    'surname': 'Doe',
    'age': 27,
    'hair_color': 'green',
}

"object person is some instance of class representing person"
person.name = my_dict['name']
person.surname = my_dict['surname']
person.age = my_dict['age']
person.hair_color = my_dict['hair_color']

我认为这是很多重复。 你使用什么方法?


I very often need to do something like this:

"Some dictionary with values obtained somehow (e.g. submitted form values)"
my_dict = {
    'name': 'John',
    'surname': 'Doe',
    'age': 27,
    'hair_color': 'green',
}

"object person is some instance of class representing person"
person.name = my_dict['name']
person.surname = my_dict['surname']
person.age = my_dict['age']
person.hair_color = my_dict['hair_color']

I think this is a lot of repetition. What approach do you use?


原文:https://stackoverflow.com/questions/12569014
更新时间:2023-11-28 11:11

最满意答案

您不能将插入作为成员函数重载到ostream ,因为第一个参数是ostream 。 你需要使它成为一个免费的功能:

std::ostream& operator<<(std::ostream&, Card const &);

您重载的运算符必须被调用为:

Card c;
c << std::cout;

这是非常单一的。


You cannot overload insertion into a ostream as a member function as the first argument is the ostream. You need to make it a free function:

std::ostream& operator<<(std::ostream&, Card const &);

The operator that you overloaded would have to be called as:

Card c;
c << std::cout;

Which is quite unidiomatic.

相关问答

更多
  • 这条线的问题: int res = o1 + o2; 是你的operator +重载返回一个Operators类型的对象。 这意味着您正在尝试从类型为Operators的临时值( o1 + o2的结果res)初始化int ( res) ),但是没有用户定义的转换。 这就是编译器发出错误的原因。 您可以通过向Operators类添加转换运算符来轻松解决此问题: operator int () const { return num1; } 更新: 看来你已经更新了你的问题。 下面的第二行是有问题的: Ope ...
  • 我强烈建议将OPTION STRICT设置为ON ,当您尝试从签名将Integer定义为返回类型的方法返回Boolean时,您的代码甚至不会编译。 这有助于避免错误 IEqualityComparer接口用于定义您自己的相等定义,可以在此接口用于指定相等性的任何位置使用,例如在Hashtable , NameValueCollection或OrderedDictionary的构造函数中。 如果要在自定义类型上使用=运算符,则需要重载它 : Public Shared Operator =(ByVal hum ...
  • 不,你不能在C中这样做。如果你想重载运算符,请使用C ++。 如果您想要一种类似C ++对象的行为, 可以将函数指针放在结构中。 No, you can't do that in C. Use C++ if you want to overload operators. You can put function pointers inside a structure if you want a sort of C++ object-like behaviour.
  • 您不能将插入作为成员函数重载到ostream ,因为第一个参数是ostream 。 你需要使它成为一个免费的功能: std::ostream& operator<<(std::ostream&, Card const &); 您重载的运算符必须被调用为: Card c; c << std::cout; 这是非常单一的。 You cannot overload insertion into a ostream as a member function as the first argument is th ...
  • 据我了解,对于由成员函数重载的任何运算符,该运算符左侧应该有同一个类的对象。 这将适用于任何二元运算符。 增量前和后增量,以及解引用运算符( *obj )都是一元运算符。 它们只有一个参数(函数参数或隐含的“this”参数,取决于您如何重载操作符)以及重载操作符,此唯一参数必须是类类型。 但是当我调用这个++前缀重载操作符时,我不需要左侧的Test类的任何对象。 一元运算符没有“左”和“右”两侧(操作数),它们只有一个操作数。 请记住,在你的情况下: ++t; 意味着: t.operator++(); ...
  • Foo::operator=两个重载都是用于重载决策目的的同样好的匹配 - 因此模糊。 Bar::operator=的情况并非如此 - 其他条件相同,重载解析更喜欢模板上的非模板。 所以私有operator=是一个更好的匹配 - 但当然它失败了访问检查。 Foo(f2)是临时的,不能绑定到非const引用。 以值为参数的过载是唯一可行的候选者。 它没有优先考虑引用过载 - 它优先考虑非模板重载。 您可以通过切换它们来确认。 Both overloads of Foo::operator= are ...
  • 您可能会重载自定义容器上的[]运算符,以提供访问元素的语义/语义更清晰的方式。 例如my_container[3] = 9; 比my_container.set(3, 9);更清晰my_container.set(3, 9); 当然,你可以重载[]基本上做任何事情,但你可能不应该。 例如,您可以使my_object[3]将my_object增加3,但语义上[]运算符会传递按索引查找,并且最好让您的接口符合预期。 你可以使用assert进行快速和肮脏的边界检查; 它会导致你的程序混乱死亡,这总是比引入细微的内 ...
  • 你重载的是预增量运算符。 你正在使用的是后增量运算符。 您可以使用预增量运算符: ++(*this); 或者实现一个后增量的oprator: void operator++(int) { ... } 要成为惯用语,您应该更改这些函数的返回值。 Zealot& operator++() { ... } Zealot operator++(int) { ... } 您可以在http://en.cppreference.com/w/cpp/language/operators上阅读有关运算符重载的更多信息。 ...
  • 正如Bjarne Stroustrup在D&E书中所说: 但是,即使在C ++的原始设计中,我也限制了运算符[] , ()和->成为成员。 这似乎是一种无害的限制,消除了一些模糊错误的可能性,因为这些操作符总是依赖于并且通常会修改其左操作数的状态。 然而,这可能是一种不必要的保姆主义。 As Bjarne Stroustrup says in the D&E book: However, even in the original design of C++, I restricted operators [ ...
  • 重载运算符没有任何性能损失。 它转换为常规函数调用。 运算符重载的优点仅在于它使代码更短。 但是,在数组乘法的情况下,我建议使用一个正确命名的函数,因为向量至少有两种乘法语义 - 有元素乘法,并且有点积乘以标量乘法。 重载运算符*将使含义模糊不清。 Overloading operators does not have any performance penalty. It translates to a regular function call. The advantage of operator ov ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)