Last active
July 3, 2019 13:43
-
-
Save crodriguez1a/e4f0f0b5b711ff08bdd2d634ba067e9b to your computer and use it in GitHub Desktop.
Pythonic Getters and Setters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Customer: | |
__slots__ = ['member_discount'] | |
def __init__(self, member_discount:float): | |
self.member_discount = member_discount | |
class Product: | |
__slots__ = ['_price', '_discounted_price', '_color_way'] | |
def __init__(self, price:float, discounted_price:float, color_way:str,): | |
self._price = price | |
self._discounted_price = discounted_price | |
self._color_way = color_way | |
@property | |
def color_way(self): | |
return self._color_way | |
@property | |
def price(self): | |
return self._price | |
@property # -> getter | |
def discounted_price(self) -> float: | |
return self._discounted_price | |
@discounted_price.setter # -> setter | |
def discounted_price(self, value:float): | |
self._discounted_price = value | |
# data retrieved from API | |
product_data:dict = { 'price': 50., 'discounted_price': 0, 'color_way': 'red+black' } | |
customer_data:dict = {'member_discount': .25 } | |
# hydrate customer | |
customer:Customer = Customer(**customer_data) | |
# hydrate product | |
sneakers:Product = Product(**product_data) | |
# calculate discount | |
def calc_discount(price:float, discount:float) -> float: | |
return price - (price * discount) | |
# apply discount only for specific color way | |
if sneakers.color_way == 'red+black': | |
# simple property assignment uses `setter` under the hood | |
sneakers.discounted_price = calc_discount(sneakers.price, customer.member_discount) | |
print('after discount: ', sneakers.discounted_price) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment