DEV Community

Brandon Michael Hunter
Brandon Michael Hunter

Posted on

1

What I learned today 5.8.24

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")`
Enter fullscreen mode Exit fullscreen mode

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay