forked from brianbryank/AirBnB_clone
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Define all common attributes/methods for other classes
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
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__) |