Parameter types and property encapsulation in Python
Cool Python things which people should be using
I just discovered a couple of cool new Python things that I don’t understand why people aren’t using.
It turns out that you can do this:
def test(name:str, age:int):
pass
But don’t get too excited because the runtime will still let people pass in anything they want so you still need to type check and throw exceptions yourself where appropriate. It’s useful for self-documenting your code, but still…really??
class Person:
def __init__(self, name):
self.name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, var):
self.__name = var
Property encapsulation! I’m very happy about this.
If you’re new to programming this is great because it allows you to hide how you store something within your class (which means you can change it later without breaking code all over the place) and more importantly, allows you to insert validation and business rules. Eg: you can make sure person.age can’t be set to a negative number, or check the new product you’re trying to add to this customer isn’t incompatible with anything they already have.
Yes I know i can do the same thing with person.get_name() and person.set_name("") but I’m old and set in my ways and I think it’s butt-ugly. Sue me.