-
Notifications
You must be signed in to change notification settings - Fork 1
/
base_model.py
executable file
·67 lines (57 loc) · 1.97 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/python3
"""
Module containing a base class from which other classes wiil inherit
"""
from uuid import uuid4
from datetime import datetime
from models import storage
class BaseModel:
"""Base class from which other classes will inherit from
Attributes:
id(str): uuid
created_at: timestamp of the creation day of the class
updated_at: timestamp of the update day of the class
"""
def __init__(self, *args, **kwargs):
"""Initializes the class object
Args:
*args(args): variable length of arguements
**kwargs(dict): keyworded variable length of arguements
"""
FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
if not kwargs:
self.id = str(uuid4())
self.created_at = datetime.utcnow()
self.updated_at = datetime.utcnow()
storage.new(self)
else:
for key, value in kwargs.items():
if key == "created_at" or key == "updated_at":
self.__dict__[key] = datetime.strptime(
value, FORMAT)
else:
self.__dict__[key] = value
def save(self):
"""
Updates updated_at with modification date timestamp
"""
self.updated_at = datetime.utcnow()
storage.save()
def to_dict(self):
"""
Returns a dict containing all keys/values of __dict__ of the instance
"""
dict_map = {}
for key, value in self.__dict__.items():
if key == "created_at" or key == "updated_at":
dict_map[key] = value.isoformat()
else:
dict_map[key] = value
dict_map["__class__"] = self.__class__.__name__
return dict_map
def __str__(self):
"""
Returns a string representation of the class
"""
class_name = self.__class__.__name__
return "[{}] ({}) {}".format(class_name, self.id, self.__dict__)