格式化字符串中的python dict [复制](python dict in formatted string [duplicate])
这个问题在这里已经有了答案:
我想在字符串中写一个python字典。 项目的值应由格式化的字符串给出。
我期望以下工作,但它不会,因为用于定义dict的第一个'{'被解释为格式化字段
In: "{'key_1': '{value}'}".format(**{'value': 'test'})
以下工作正常,但不返回预期的字典:
In: "'key_1': '{value}'".format(**{'value': 'test'}) Out: "'key_1': 'test'"
克服这个问题的一种方法是使用list brakets并稍后用dict brakets替换它们:
In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}') Out: "{'key_1': 'test'}"
如何以更好的方式写这个?
This question already has an answer here:
I want to write a python dictionary in a string. The values of the items should be give by the formatted string.
I expected the following to work, but it doesnt because the first '{' used to define the dict is interpreted as a formated field
In: "{'key_1': '{value}'}".format(**{'value': 'test'})
the following works fine, but doesn't return the expected dict:
In: "'key_1': '{value}'".format(**{'value': 'test'}) Out: "'key_1': 'test'"
one way to overcome the problem is by using list brakets and replace them later by the dict brakets:
In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}') Out: "{'key_1': 'test'}"
How to write this in a better way?
原文:https://stackoverflow.com/questions/30394912
最满意答案
将
Base
类引用分配给Derived
类引用变量是非法的。
X
类型的变量只能是对X
类型或派生类型的对象的引用。您可能需要另一个包含与现有对象相同数据的
SpecialContact
实例。 没有办法避免手动复制。当我需要将匹配属性从一个对象复制到另一个不兼容的对象时,我使用以下扩展方法(1):
public static void AssignFrom(this object destination, object source) { Type dest_type = destination.GetType(); Type source_type = source.GetType(); var matching_props = from d in dest_type.GetProperties() join s in source_type.GetProperties() on d.Name equals s.Name where d.IsWritable() && s.IsReadable() select new { source = s, destination = d }; foreach (var prop in matching_props) { prop.destination.SetValue(destination, prop.source.GetValue(source, null), null); } }
那你可以这样做:
specialContact.assignFrom(contact);
请考虑这个解决方法。 正确的解决方案是正确设计您的类层次结构,而您不会遇到此问题。
1注意:它按名称匹配属性并假定它们属于同一类型。
It is illegal to assign
Base
class reference to theDerived
class reference variable.Variable of type
X
can only be a reference to an object of typeX
or derived.You probably need to have another instance of
SpecialContact
which contains the same data as existing object. There is no way to avoid manual copying.I use the following extension method when I need to copy the matching properties from one object to another incompatible one(1):
public static void AssignFrom(this object destination, object source) { Type dest_type = destination.GetType(); Type source_type = source.GetType(); var matching_props = from d in dest_type.GetProperties() join s in source_type.GetProperties() on d.Name equals s.Name where d.IsWritable() && s.IsReadable() select new { source = s, destination = d }; foreach (var prop in matching_props) { prop.destination.SetValue(destination, prop.source.GetValue(source, null), null); } }
Then you can do:
specialContact.assignFrom(contact);
Please consider this a workaround. The proper solution would be to design properly your class hierarchy where you do not come to this problem.
1 Note: it matches the properties by name and assumes they are of the same type.
相关问答
更多-
不,没有内置的方式来转换类似你说的话。 最简单的方法就是做你所建议的:创建一个DerivedClass(BaseClass)构造函数。 其他选项基本上可以自动化从基础到派生实例的属性复制,例如使用反射。 您发布的代码将会编译,因为我确信你已经看到了,但是当您运行它时会抛出一个空引用异常,因为由于myBaseObject as DerivedClass将会为null ,因为它不是DerivedClass的一个实例。 No, there's no built-in way to convert a class ...
-
StopsVisited不是Stops
的子类型; 它是Stops 的一个子类型,这是完全不同的东西。 我同意duffymo的观点:子类型是对你的问题的错误方法,但是你提到的特定功能在C#4中被称为“协方差”或“输出安全”; 你可以在这里阅读。 StopsVisited is not a subtype of Stops ; it's a subtype of Stops , which is an entirely different t ... -
如果您可以更改创建代码,那么您可能会忽略这一点: template
void deleter(void* p){ delete static_cast (p); } template class Container{ private: T* obj; typedef void (*deleter_func)(void*); deleter_func obj_deleter; public: Container(T* o, deleter_fu ... -
p是Parent的实例,因此您无法告诉运行时将其解释为一个。 编译器没有捕获它,因为这样的代码 Parent p = new Child(); Child c = (Child)p; 并且编译器不进行捕获它所需的静态代码分析。 不检查的原因是: 这很费时间 它只能捕获一些错误实例。 p is an instance of Parent, so you cannot tell the runtime to interpret it as one. The compiler does not catch ...
-
向下转换为派生类(Casting to derived class downward)[2021-07-31]
不确定这是否是您需要的,但您可以拥有一个“知道”派生类型的基类: class MyBase{} class A : MyBase {} class B : MyBase {} 这样你可以这样做: void Foo(MyBase baseObj) { T derived = (T)(object)baseObj; // use derived in a strongly-typed manner } Not exactly sure if this is wh ... -
将类转换为派生类(Transform class to a derived class)[2023-10-15]
将Base类引用分配给Derived类引用变量是非法的。 X类型的变量只能是对X类型或派生类型的对象的引用。 您可能需要另一个包含与现有对象相同数据的SpecialContact实例。 没有办法避免手动复制。 当我需要将匹配属性从一个对象复制到另一个不兼容的对象时,我使用以下扩展方法(1): public static void AssignFrom(this object destination, object source) { Type dest_type = destination.GetTyp ... -
在创建对象后,无法更改对象的类型(构造和销毁除外,派生类对象暂时变为基类对象)。 由于派生类对象可能比它们的基类大,因此也无法使用它。 创建新派生对象,重置指针然后销毁基础对象的方法是有效的,如果没有其他人持有另一个指向基类的指针。 如果有任何其他指针或对原始对象的引用,它将在之后悬空。 但是如果你控制了该类的唯一指针/引用(例如,如果你只通过一个从不泄漏指针或对真实对象的引用的单例代理对象来访问它),那么这个方法是有效的。 There is no way to change the type of an ...
-
我错过了什么以及将派生类的列表转换为其基类列表的正确方法是什么? 该列表仍包含DerivedClass实例,但它们被用作对BaseClass引用。 但是,此API的任何使用者都不会知道这一点,所以他们会将此视为BaseClass元素。 这是常见的,通常是正确的方法。 如果您需要实际将实例转换为BaseClass实例(这可能不是必需的),您需要从DerivedClass成员实际制作新的BaseClass实例,即: List
_baseClass = _derivedClass.Selec ... -
编辑:我已经增加了示例以使它们更清晰。 在演员阵容上传递通常是糟糕设计的标志。 演员有自己的位置,但这看起来并不像。 您需要问自己,您想对cBodyParts存储的对象做什么。 当然,你会Hand或Head做不同的事情,但你可能会以某种方式抽象它们:这就是虚函数的作用。 因此,除了您已经为类编写的内容之外,您还需要一个额外的虚函数: class BodyPart { // Same as you wrote, plus: public: virtual void InitialisePart() = ...
-
WCF接口和派生类(WCF interface and derived class)[2021-12-18]
如果您有派生类,则需要在数据协定上“宣传”这些类: [DataContract] [KnownType(typeof(DerivedType1))] [KnownType(typeof(DerivedType2))] public class BaseType { ...... } 或者您也可以在服务合同上指定这种关系: [ServiceKnownType(typeof(DerivedType1))] [ServiceKnownType(typeof(DerivedType2))] [Ser ...