Trying to cast one object type into another in Python

眉间皱痕 提交于 2021-01-27 21:27:16

问题


I have this bit of code:

const ON_Curve* curve = ...;

const ON_NurbsCurve* nurb = ON_NurbsCurve::Cast( curve );
if( nurb )
{
ON_Ellipse ellipse;
double tolerance = model.m_settings.m_ModelUnitsAndTolerances.m_absolute_tolerance;
bool rc = nurb->IsEllipse( 0, &ellipse, tolerance );

It casts a ON_NurbsCurve object to ON_Curve object. I am not quite sure if that's even possible in Python. I know i can take a string and cast it into an integer like: int("1"). I am not sure what is the right way to do so with other object types that are not built in.

thank you


回答1:


You can't exactly cast objects in Python, nor do you generally need to because Python doesn't have strong type-checking.

Technically, casting is interpreting an existing object's data as if it were another type, essentially treating the object as a liquid metal that is being cast into a new shape (the origin of the term). In Python, what you can do is try to convert an object to another format. Usually an object that can take another object as input will accept it in its constructor (e.g. int() can take strings as well as numbers, and will call __int__() on other types if such a method exists, to let other types define how they are converted). Some types even have alternate constructors if their main constructor can't accept a given kind of object (for example, an XML parser might accept a filename in its main constructor, and have from_string() and from_file() class methods that accept strings and file-like objects, respectively).

In the example you give, of converting one type of Curve object into another, in Python you probably wouldn't even need to do any conversion. The NurbsCurve object probably supports the methods and attributes of Curve that any function that accepts a Curve would expect to see, even if it isn't a strict subclass. And if it is a strict subclass, then there's definitely no problem and no need to convert!

Python doesn't check argument types unless there is explicit code to do so, and most functions don't have such code. Instead, they just assume the caller is not a doofus and has passed in an object they can use. This is commonly called "duck typing."

If a given function doesn't accept the object you want to pass in, you could write a conversion function, a multiple-inheritance subclass, or a wrapper class to make what you have behave enough like the type that's needed to get the function to work. But this is usually not needed, because people who design APIs are not idiots and will be generous in what they accept when possible.



来源:https://stackoverflow.com/questions/31550983/trying-to-cast-one-object-type-into-another-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!