像下面这样简单的东西对你有用吗?
在对象实例化时,检查是否提供了太多或太少的数据,然后定义一个在必要时将计算值的属性?
class Item ():
def __init__(self, id: int =None, name:str= None):
if all ([name, id]):
raise ValueError ("id_ and name cannot be provided together")
elif not any ([name, id]):
raise ValueError ("name or id must be provided for Item instantiation")
else:
self._name = name
self._id = id
@property
def name (self) -> str:
if self._name is None:
#Compute the value and return it
pass #remove this once you figure out your algorithm
else:
return self._name
@property
def id (self) ->int:
if self._id is None:
#Compute the value and return it
pass #remove this once you figure out your algorithm
else:
return self._id
请注意,您还必须考虑什么是有效值。0
在我提供的示例案例中,如果您认为整数是有效的id
,而空字符串""
是有效的是不够的name
。