Created
February 5, 2017 13:49
-
-
Save vskrachkov/1916e36ca65ab9bc3f4d2016bef2d5b3 to your computer and use it in GitHub Desktop.
Usage of built-in class `property`
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_property.py | |
================= | |
Shows how to use python's built-in class 'property' for implementation of | |
encapsulation by pythonic way. | |
Use 'python3 -i class_property' for testing Man class interfaces. | |
Instance of this class will be already initialized as 'man' variable. | |
***Pay special attention to birth_date and birth_year properties*** | |
""" | |
import datetime | |
class Man: | |
"""Sample class in which @property uses for encapsulation. | |
""" | |
def __init__(self, first_name, last_name, age): | |
self.first_name = first_name | |
self.last_name = last_name | |
self.age = age | |
self._birthdate = None | |
self.anonymous = False | |
def __repr__(self): | |
return f'Man: {self.full_name}' | |
@property | |
def _current_datetime(self): | |
return datetime.datetime.now() | |
@property | |
def full_name(self): | |
if not self.anonymous: | |
return ' '.join((self.first_name, self.last_name)) | |
return 'Anonymous' | |
@full_name.setter | |
def full_name(self, val): | |
try: | |
self.first_name, self.last_name = val.split(' ') | |
except: | |
print('You must set the first name and the last name.') | |
@full_name.deleter | |
def full_name(self): | |
self.first_name = 'Anonymous' | |
self.last_name = 'Anonymous' | |
self.anonymous = True | |
@property | |
def birth_year(self): | |
now = self._current_datetime | |
return now.replace(year=now.year-self.age).year | |
@property | |
def birthdate(self): | |
if self._birthdate: | |
return self._birthdate | |
raise AttributeError('birthdate not setted yet.') | |
@birthdate.setter | |
def birthdate(self, val): | |
if isinstance(val, datetime.datetime): | |
self.age = (self._current_datetime - val).days // 365 | |
self._birthdate = val | |
man = Man(first_name='Ben', last_name='Dowson', age=18) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment