-
Notifications
You must be signed in to change notification settings - Fork 3
/
base_model.py
executable file
·61 lines (52 loc) · 2.05 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
#!/usr/bin/python3
"""BaseModel class"""
import models
import uuid
from datetime import datetime
class BaseModel:
"""BaseModel class to be inherited by other classes"""
def __init__(self, *args, **kwargs):
"""__init__ method & instantiation of class Basemodel"""
self.id = str(uuid.uuid4())
self.created_at = datetime.now()
self.updated_at = self.created_at
for name, value in kwargs.items():
"""searches through dict for keys"""
if name == "__class__":
continue
setattr(self, name, value)
if "id" not in kwargs:
models.storage.new(self)
def __setattr__(self, name, value):
"""Maintain correct types for non-string attributes while keeping
the attributes as public attributes.
Args:
name (str): name of attribute
value: value to associate with `name`
Raises:
AttributeError: If value cannot be parsed into correct format
"""
if name in ['created_at', 'updated_at']:
if isinstance(value, str):
try:
value = datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')
except ValueError:
raise AttributeError("Invalid value: ({}) for name: ({})"
.format(value, name))
super().__setattr__(name, value)
def __str__(self):
"""Format `self` for output"""
return "[{}] ({}) {}".format(self.__class__.__name__,
self.id, self.__dict__)
def save(self):
"""updates the public instance attribute updated_at"""
self.updated_at = datetime.now()
models.storage.save()
def to_dict(self):
"""returns a dictionary containing all key/value pairs of __dict__"""
d = {}
d.update(self.__dict__)
d['created_at'] = d['created_at'].isoformat()
d['updated_at'] = d['updated_at'].isoformat()
d['__class__'] = self.__class__.__name__
return d