我有一个带有构造函数和几个属性的类
class Foo(object):
def __init__(self, value1):
self._value1 = value1
@property
def value1(self):
return self._value1
@property.setter
def value1(self, value):
assert value == 1
self._value1 = value
现在,当我在创建对象时设置value1时,不使用setter。我注意到了这一点,因为在输入错误的值时没有调用断言。
如何让构造函数中设置的值使用setter?
答案 0 :(得分:3)
您通过设置基础变量而不是使用属性明确绕过setter。删掉下划线。
def __init__(self, value1):
self.value1 = value1
答案 1 :(得分:1)
解决方案?
class Foo(object):
def __init__(self, value1 = 0):
self.value1 = value1 # Calling Set Property
@property
def value1(self):
return self.__value1
@property.setter
def value1(self, value):
assert value == 1
self.__value1 = value
其他示例...
示例1
class Product(object):
def __init__(self, price = 0.0):
self.price = price
def get_price(self):
return self.__price
def set_price(self, value):
if value < 0:
raise ValueError("Price cannot be negative")
self.__price = value
price = property(get_price, set_price)
示例2
class Product(object):
def __init__(self, price = 0.0, name = ""):
self.price = price
self.name = name
# property for __price attribute
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("Price cannot be negative")
self.__price = value
# property for __name attribute
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
for ch in value:
if ch.isdigit():
raise Exception("Enter valid product name")
self.__name = value
PythonDevelopment #MachineLearning #ComputerVision #NLP #DataScience #DeepLearning #NeuralNetworks #IoT #WebDevelopment #WebScraping