[英]Python property does not use setter when setting the value in the constructor
I have a class with a constructor and a couple of properties我有一个带有构造函数和几个属性的类
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
Now when I set value1 in on creation of the object the setter is not used.现在,当我在创建对象时设置 value1 时,不使用 setter。 I noticed this because assertions were not called when entering the wrong values.
我注意到这一点是因为在输入错误的值时没有调用断言。
How can I make the values set in the constructor make use of the setter?如何使构造函数中设置的值使用 setter?
You're explicitly bypassing the setter by setting the underlying variable, rather than using the property.您通过设置底层变量而不是使用属性来显式绕过 setter。 Drop the underscore.
去掉下划线。
def __init__(self, value1):
self.value1 = value1
Solution 😊解决方案😊
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
Other Examples ...其他例子...
Example 1示例 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)
Example 2示例 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
PythonDevelopment #MachineLearning #ComputerVision #NLP #DataScience #DeepLearning #NeuralNetworks #IoT #WebDevelopment #WebScraping
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.