-
Notifications
You must be signed in to change notification settings - Fork 2
/
base_model.py
44 lines (39 loc) · 1.67 KB
/
base_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python3
"""This module defines a base class for all models in our hbnb clone"""
import uuid
from datetime import datetime
class BaseModel:
"""A base class for all hbnb models"""
def __init__(self, *args, **kwargs):
"""Instatntiates a new model"""
if not kwargs:
from models import storage
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = datetime.now()
storage.new(self)
else:
kwargs['updated_at'] = datetime.strptime(kwargs['updated_at'],
'%Y-%m-%dT%H:%M:%S.%f')
kwargs['created_at'] = datetime.strptime(kwargs['created_at'],
'%Y-%m-%dT%H:%M:%S.%f')
del kwargs['__class__']
self.__dict__.update(kwargs)
def __str__(self):
"""Returns a string representation of the instance"""
cls = (str(type(self)).split('.')[-1]).split('\'')[0]
return '[{}] ({}) {}'.format(cls, self.id, self.__dict__)
def save(self):
"""Updates updated_at with current time when instance is changed"""
from models import storage
self.updated_at = datetime.now()
storage.save()
def to_dict(self):
"""Convert instance into dict format"""
dictionary = {}
dictionary.update(self.__dict__)
dictionary.update({'__class__':
(str(type(self)).split('.')[-1]).split('\'')[0]})
dictionary['created_at'] = self.created_at.isoformat()
dictionary['updated_at'] = self.updated_at.isoformat()
return dictionary