class Tribool(object):
def __init__(self, value = None):
if any(value is v for v in (False, True, None)):
self.value = value
else:
raise ValueError("Tribool must be False, True or None")
def __nonzero__(self):
raise TypeError("Tribool may not be used as an implicit bool")
def __eq__(self, other):
if isinstance(other, Tribool):
return self.value is other.value
if any(other is v for v in (False, True, None)):
return self.value is other
raise TypeError("Tribool can only be compared to another Tribool or False, True, or None")
def __ne__(self, other):
return not (self == other)
def __invert__(self):
if self.value is False:
return Tribool(True)
elif self.value is True:
return Tribool(False)
elif self.value is None:
return Tribool(None)
raise ValueError("Tribool must be False, True or None")
def __and__(self, other):
if (self.value is False) or (other.value is False):
return Tribool(False)
if (self.value is None) or (other.value is None):
return Tribool(None)
return Tribool(True)
def __or__(self, other):
if (self.value is True) or (other.value is True):
return Tribool(True)
if (self.value is None) or (other.value is None):
return Tribool(None)
return Tribool(False)
def __xor__(self, other):
if (self.value is None) or (other.value is None):
return Tribool(None)
if self == other:
return Tribool(False)
return Tribool(True)
def __str__(self):
if any(self.value is v for v in (False, True, None)):
return str(self.value)
raise ValueError("Tribool must be False_, True_ or Maybe_")
def __repr__(self):
return "Tribool(%s)" % str(self)
我认为我需要编写一个to_python_转换器,但我无法想出如何为用户定义的python类型编写转换器。我已经阅读了boostpython文档,并使用Google进行了搜索,但没有找到一个好的示例。感谢任何帮助。在
更新:
以下C++代码将将TRIPBOL转换为Python值TRUE、FALSE和NORE,这是部分解决方案:
^{pr2}$我无法理解的部分是如何返回纯Python Tribool类的实例,而不是从转换例程返回值True、False和None。在
这可以用与从Python方法返回
Tribool
相同的方式完成。在这两种语言中,都需要获得Tribool
Python类对象的句柄,然后调用它。返回的对象将是Tribool
类型的实例。在例如:
相当于:
^{pr2}$下面是一个简化的例子,其中用户定义的Python模块(^ {CD4>})包含Python类(^ {CD5>}),而C++ Python扩展模块(^ {CD6>})提供了一个^ {CD7>}函数,创建了^ {CD8>}对象。在
spam.py
Python模块:example.cpp
扩展模块:交互式Python:
相关问题 更多 >
编程相关推荐