class Product:
def init(self, price):
self.price = price
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("The price cannot be negative")
self.__price = value
product1 = Product(40)
product1.price = 20
print(product1.price)
Here I cannot understand where and how we are using self.__price in properties, while we are not using it at the time of defining the reference object
Hi, init is the constructor method here (note it should be preceeded and followed by double underscore ie: init ). We pass this method a value and this value will initially give the product object (when the Product class is instantiated) that value for its price field.
The self keyword is a reference to the current instance (object) from this Product class blueprint.
@property - this is a decorator to make its associated method a getter function to read the value of the price field that is initialized above.
@price.setter - this is a decorator to make its assoicated method a setter function to update the value of the price field. This is why we have validation logic to make sure the price is not negative
product1 = Product(40)
product1.price = 20
print(product1.price)
for this code we are passing 40 as the price to give it this value upon starting for the product1 object, we then set the price to 20 and print it
I recently decided to try a do my engineering assignment for me service, and it was a lifesaver! I was stuck on a complicated project involving circuit design, and the expert help I received made everything so much easier to understand. The assignment was well-done, delivered on time, and it really improved my overall grade. If you’re struggling with tough engineering coursework, I’d definitely recommend using this service for reliable support.