Here's what I learned today from studying Python.....
I didn't know defining a class property with '__' in Python its referred as private.
In this example the property '.__height', if you try to set it will throw an Attribute error.
`class Square:
def init(self):
self.height = 2
self.width = 2
def set_side(self, new_side):
self.height = new_side
self.width = new_side
square = Square()
square.__height = 3 # raises AttributeError `
There's a caveat...... You can still set the class property by using the following code:
square = Square()
square._Square__height = 3 # is allowed
The solution is uses decorators for our getters and setters methods. This allows us to validate the data before setting the internal __height property value. Check out the code below.
`class Square:
def init(self, w, h):
self.height = h
self.width = w
def set_side(self, new_side):
self.__height = new_side
self.__width = new_side
**@property**
def height(self):
return self.__height
**@height.setter**
def height(self, new_value):
if new_value >= 0:
self.__height = new_value
else:
raise Exception("Value must be larger than 0")`
Decorators are functions that take your function as input. This will allow you to decorate one function and then reuse and add the decorated function on different function to extend the new function's capabilities. Pretty cool.
That's it. Let me know what you think and/or correct anything I missed.
Thanks for stopping by,
Cheers
Top comments (0)