Owlready2为多类创建FunctionalProperty遇TypeError问题求助
解决Owlready2中多类设置FunctionalProperty域的TypeError问题
问题说明
需要在Python的Owlready2库中,为6个继承自Thing的类(例如student、teacher)创建FunctionalProperty,并指定这些类作为属性的域。
示例类定义:
class student(Thing): pass class teacher(Thing): pass # 共6个此类结构的类
参考了多域设置的写法,比如:
class has_color(ObjectProperty): domain = [Or([Car,Bike,House])] range = [Color]
或者:
domain = [Car | Bike | House]
但当给5个及以上类设置域时,运行以下代码报错:
class has_value(FunctionalProperty): domain = [ Or(myclass1, myclass2, myclass3, myclass4, myclass5, myclass6) ] range = [float]
错误信息:
Exception has occurred: TypeError
LogicalClassConstruct.init() takes from 2 to 4 positional arguments but 6 were given
解决方法
报错原因是Owlready2的Or构造函数直接传递多个位置参数时,最多支持4个参数。解决方式有两种:
方法1:将类放入列表传递给Or
把所有需要设置为域的类打包成一个列表,作为Or的参数:
class has_value(FunctionalProperty): domain = [Or([myclass1, myclass2, myclass3, myclass4, myclass5, myclass6])] range = [float]
方法2:使用链式|操作符
通过|运算符链式拼接多个类,这种方式支持任意数量的类:
class has_value(FunctionalProperty): domain = [myclass1 | myclass2 | myclass3 | myclass4 | myclass5 | myclass6] range = [float]
以上两种写法都可以避免参数数量超限的问题,成功为多个类设置FunctionalProperty的域。
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

