我有这个:
def required(props):
props.fget.required = True
return props
class SomeClass():
@required
@property
def func(self):
return self.conname("conname")
但是我想要这样:当SomeClass的self.name属性等于“value”时,当需要非等等假时,使属性可选。
答案 0 :(得分:0)
您可以在初始化程序中处理此问题,如下所示:
class SomeClass(object): # inherit from object if you are using python 2.7
def __init__(self, name, optional_required_property=None):
self.name = name
if name == "value" and optional_required_property is None:
raise AttributeError("optional_required_property cannot be None.")
else:
self.optional_required_property = optional_required_property
test_someclass = SomeClass("test") # will work
test_someclass = SomeClass("value") # will fail
受Stack Overflow Question: How to implement a required property in Python启发