Skip to content

Commit

Permalink
Define all common attributes/methods for other classes
Browse files Browse the repository at this point in the history
  • Loading branch information
mwongess committed Jan 29, 2022
1 parent 88aeba0 commit 6d72b5f
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions models/base_model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/python3
"""Defines the BaseModel class."""
import models
from uuid import uuid4
from datetime import datetime


class BaseModel:
"""Represents the BaseModel of the HBnB project."""

def __init__(self, *args, **kwargs):
"""Initialize a new BaseModel.
Args:
*args (any): Unused.
**kwargs (dict): Key/value pairs of attributes.
"""
tform = "%Y-%m-%dT%H:%M:%S.%f"
self.id = str(uuid4())
self.created_at = datetime.today()
self.updated_at = datetime.today()
if len(kwargs) != 0:
for k, v in kwargs.items():
if k == "created_at" or k == "updated_at":
self.__dict__[k] = datetime.strptime(v, tform)
else:
self.__dict__[k] = v
else:
models.storage.new(self)

def save(self):
"""Update updated_at with the current datetime."""
self.updated_at = datetime.today()
models.storage.save()

def to_dict(self):
"""Return the dictionary of the BaseModel instance.
Includes the key/value pair __class__ representing
the class name of the object.
"""
rdict = self.__dict__.copy()
rdict["created_at"] = self.created_at.isoformat()
rdict["updated_at"] = self.updated_at.isoformat()
rdict["__class__"] = self.__class__.__name__
return rdict

def __str__(self):
"""Return the print/str representation of the BaseModel instance."""
clname = self.__class__.__name__
return "[{}] ({}) {}".format(clname, self.id, self.__dict__)

0 comments on commit 6d72b5f

Please sign in to comment.