Class and Object Terms

The foundations of Object-Oriented Programming is defining a Class

  • In Object-Oriented Programming (OOP), a class is a blueprint for creating an Object. (a data structure). An Object is used like many other Python variables.
  • A Class has ...
    • a collection of data, these are called Attributes and in Python are pre-fixed using the keyword self
    • a collection of Functions/Procedures. These are called *Methods when they exist inside a Class definition.
  • An Object is created from the Class/Template. Characteristics of objects ...
    • an Object is an Instance of the Class/Template
    • there can be many Objects created from the same Class
    • each Object contains its own Instance Data
    • the data is setup by the Constructor, this is the "init" method in a Python class
    • all methods in the Class/Template become part of the Object, methods are accessed using dot notation (object.method())
  • A Python Class allow for the definition of @ decorators, these allow access to instance data without the use of functions ...
    • @property decorator (aka getter). This enables developers to reference/get instance data in a shorthand fashion (object.name versus object.get_name())
    • @name.setter decorator (aka setter). This enables developers to update/set instance data in a shorthand fashion (object.name = "John" versus object.set_name("John"))
    • observe all instance data (self._name, self.email ...) are prefixed with "", this convention allows setters and getters to work with more natural variable name (name, email ...)

Class and Object Code

# A gateway in necessary as a web server cannot communicate directly with Python.
# In this case, imports are focused on generating hash code to protect passwords.
from werkzeug.security import generate_password_hash, check_password_hash
import json

# Define a User Class/Template
# -- A User represents the data we want to manage
class User:    
    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, uid, password):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)

    # a name getter method, extracts name from object
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts email from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
    @property
    def password(self):
        return self._password[0:10] + "..." # because of security only show 1st characters

    # update password, this is conventional setter
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # check password parameter versus stored/encrypted password
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
    # output content using str(object) in human readable form, uses getter
    def __str__(self):
        return f'name: "{self.name}", id: "{self.uid}", psw: "{self.password}"'

    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'Person(name={self._name}, uid={self._uid}, password={self._password})'


# tester method to print users
def tester(users, uid, psw):
    result = None
    for user in users:
        # test for match in database
        if user.uid == uid and user.is_password(psw):  # check for match
            print("* ", end="")
            result = user
        # print using __str__ method
        print(str(user))
    return result
        

# place tester code inside of special if!  This allows include without tester running
if __name__ == "__main__":

    # define user objects
    u1 = User(name='Thomas Edison', uid='toby', password='123toby')
    u2 = User(name='Nicholas Tesla', uid='nick', password='123nick')
    u3 = User(name='Alexander Graham Bell', uid='lex', password='123lex')
    u4 = User(name='Eli Whitney', uid='eli', password='123eli')
    u5 = User(name='Hedy Lemarr', uid='hedy', password='123hedy')

    # put user objects in list for convenience
    users = [u1, u2, u3, u4, u5]

    # Find user
    print("Test 1, find user 3")
    u = tester(users, u3.uid, "123lex")


    # Change user
    print("Test 2, change user 3")
    u.name = "John Mortensen"
    u.uid = "jm1021"
    u.set_password("123qwerty")
    u = tester(users, u.uid, "123qwerty")


    # Make dictionary
    ''' 
    The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. 
    Every object in Python has an attribute that is denoted by __dict__. 
    Use the json.dumps() method to convert the list of Users to a JSON string.
    '''
    print("Test 3, make a dictionary")
    json_string = json.dumps([user.__dict__ for user in users]) 
    print(json_string)

    print("Test 4, make a dictionary")
    json_string = json.dumps([vars(user) for user in users]) 
    print(json_string)
Test 1, find user 3
name: "Thomas Edison", id: "toby", psw: "sha256$h6I..."
name: "Nicholas Tesla", id: "nick", psw: "sha256$XPU..."
* name: "Alexander Graham Bell", id: "lex", psw: "sha256$Hc2..."
name: "Eli Whitney", id: "eli", psw: "sha256$oZ3..."
name: "Hedy Lemarr", id: "hedy", psw: "sha256$EI5..."
Test 2, change user 3
name: "Thomas Edison", id: "toby", psw: "sha256$h6I..."
name: "Nicholas Tesla", id: "nick", psw: "sha256$XPU..."
* name: "John Mortensen", id: "jm1021", psw: "sha256$Mxn..."
name: "Eli Whitney", id: "eli", psw: "sha256$oZ3..."
name: "Hedy Lemarr", id: "hedy", psw: "sha256$EI5..."
Test 3, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_password": "sha256$h6IdNO3OjBS7PVTp$9900116675f99e9d9173e43ae528d57099aa89df7a83a9968f6e7d9a526f27ba"}, {"_name": "Nicholas Tesla", "_uid": "nick", "_password": "sha256$XPUEBTr7ZjkCb02X$2e1d27f4f6af125db3e3da40a21e83577d8d647d68b32f0625935325a7b590f0"}, {"_name": "John Mortensen", "_uid": "jm1021", "_password": "sha256$Mxn3nr1DdUM9VTdP$7750935a4424c601149b37fb48f8bee942faf930b05d11e47b882a0736bc29db"}, {"_name": "Eli Whitney", "_uid": "eli", "_password": "sha256$oZ30YnYXWx4r3bRK$63dfe75e82ebff14b946bfeb10e4f4997de330bbb50d91adea8d641e5c9cf04d"}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_password": "sha256$EI5ioAAdHtsJdWGB$0536d8c3a7ccec8a2a03d7c06c3fc2ee9541b147def54ab395f058ed81cf2e73"}]
Test 4, make a dictionary
[{"_name": "Thomas Edison", "_uid": "toby", "_password": "sha256$h6IdNO3OjBS7PVTp$9900116675f99e9d9173e43ae528d57099aa89df7a83a9968f6e7d9a526f27ba"}, {"_name": "Nicholas Tesla", "_uid": "nick", "_password": "sha256$XPUEBTr7ZjkCb02X$2e1d27f4f6af125db3e3da40a21e83577d8d647d68b32f0625935325a7b590f0"}, {"_name": "John Mortensen", "_uid": "jm1021", "_password": "sha256$Mxn3nr1DdUM9VTdP$7750935a4424c601149b37fb48f8bee942faf930b05d11e47b882a0736bc29db"}, {"_name": "Eli Whitney", "_uid": "eli", "_password": "sha256$oZ30YnYXWx4r3bRK$63dfe75e82ebff14b946bfeb10e4f4997de330bbb50d91adea8d641e5c9cf04d"}, {"_name": "Hedy Lemarr", "_uid": "hedy", "_password": "sha256$EI5ioAAdHtsJdWGB$0536d8c3a7ccec8a2a03d7c06c3fc2ee9541b147def54ab395f058ed81cf2e73"}]

Hacks

Add new attributes/variables to the Class. Make class specific to your CPT work.

  • Add classOf attribute to define year of graduation
    • Add setter and getter for classOf
  • Add dob attribute to define date of birth
    • This will require investigation into Python datetime objects as shown in example code below
    • Add setter and getter for dob
  • Add instance variable for age, make sure if dob changes age changes
    • Add getter for age, but don't add/allow setter for age
  • Update and format tester function to work with changes

Start a class design for each of your own Full Stack CPT sections of your project

  • Use new code cell in this notebook
  • Define init and self attributes
  • Define setters and getters
  • Make a tester

Start Code for Hacks

from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

dob = date(2004, 12, 31)
age = calculate_age(dob)
print(age)
18
# A gateway in necessary as a web server cannot communicate directly with Python.
# In this case, imports are focused on generating hash code to protect passwords.
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date
import json

# Define a User Class/Template
# -- A User represents the data we want to manage
class User:    
    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, uid, password, classOf, dob):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)
        self._classOf = classOf
        self._dob = dob

    # a name getter method, extracts name from object
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts email from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
    @property
    def password(self):
        return self._password[0:10] + "..." # because of security only show 1st characters

    # update password, this is conventional setter
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # check password parameter versus stored/encrypted password
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
        # a classOf getter method, extracts classOf from object
    @property
    def classOf(self):
        return self._classOf
    
    # a setter function, allows classOf to be updated after initial object creation
    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf

        # a dob getter method, extracts dob from object
    @property
    def dob(self):
        return self._dob
    
    # a setter function, allows dob to be updated after initial object creation
    @dob.setter
    def dob(self, dob):
        self._dob = dob

    # output content using str(object) in human readable form, uses getter
    def __str__(self):
        return f'name: "{self.name}", id: "{self.uid}", psw: "{self.password}", classOf: "{self.classOf}", dob: "{self.dob}"'

    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'Person(name={self._name}, uid={self._uid}, password={self._password}, classOf={self._classOf}, dob={self._dob})'


# tester method to print users
def tester(users, uid, psw, classOf, dob):
    result = None
    for user in users:
        # test for match in database
        if user.uid == uid and user.is_password(psw):  # check for match
            print("* ", end="")
            result = user
        # print using __str__ method
        print(str(user))
    return result
        

# place tester code inside of special if!  This allows include without tester running
if __name__ == "__main__":

    # define user objects
    u1 = User(name='Jeffrey Lee', uid='jeff', password='123jeff', classOf='2023', dob ='12.27.04')
    u2 = User(name='Aiden Hyunh', uid='win', password='123win', classOf='2024', dob='5.12.06')
    u3 = User(name='Jagger Klein', uid='jagg', password='123jagg', classOf='2023', dob='9.18.04')
    u4 = User(name='Luke Angelini', uid='luke', password='123luke', classOf='2023', dob='7.29.04')
    u5 = User(name='James Armstrong', uid='jame', password='123jame', classOf='2024', dob='3.28.06')

    # put user objects in list for convenience
    users = [u1, u2, u3, u4, u5]

    # Find user
    print("Test 1, find user 3")
    u = tester(users, u3.uid, "123jagg", u3.classOf, u3.dob)

    # spacing
    print(" ")
    # Change user
    print("Test 2, change user 3")
    u.name = "Quandale Dingle"
    u.uid = "QD420_Wrizz"
    u.set_password("123quandale")
    u.classOf = ("2025")
    u.dob = ("1.26.54")
    u = tester(users, u.uid, "123quandale", u.classOf, u.dob)

    # spacing
    print(" ")

    # Make dictionary
    ''' 
    The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. 
    Every object in Python has an attribute that is denoted by __dict__. 
    Use the json.dumps() method to convert the list of Users to a JSON string.
    '''
    print("Test 3, make a dictionary")
    json_string = json.dumps([user.__dict__ for user in users]) 
    print(json_string)

    # spacing
    print(" ")

    print("Test 4, make a dictionary")
    json_string = json.dumps([vars(user) for user in users]) 
    print(json_string)
Test 1, find user 3
name: "Jeffrey Lee", id: "jeff", psw: "sha256$BZW...", classOf: "2023", dob: "12.27.04"
name: "Aiden Hyunh", id: "win", psw: "sha256$QqS...", classOf: "2024", dob: "5.12.06"
* name: "Jagger Klein", id: "jagg", psw: "sha256$FK3...", classOf: "2023", dob: "9.18.04"
name: "Luke Angelini", id: "luke", psw: "sha256$pYe...", classOf: "2023", dob: "7.29.04"
name: "James Armstrong", id: "jame", psw: "sha256$FAQ...", classOf: "2024", dob: "3.28.06"
 
Test 2, change user 3
name: "Jeffrey Lee", id: "jeff", psw: "sha256$BZW...", classOf: "2023", dob: "12.27.04"
name: "Aiden Hyunh", id: "win", psw: "sha256$QqS...", classOf: "2024", dob: "5.12.06"
* name: "Quandale Dingle", id: "QD420_Wrizz", psw: "sha256$pi0...", classOf: "2025", dob: "1.26.54"
name: "Luke Angelini", id: "luke", psw: "sha256$pYe...", classOf: "2023", dob: "7.29.04"
name: "James Armstrong", id: "jame", psw: "sha256$FAQ...", classOf: "2024", dob: "3.28.06"
 
Test 3, make a dictionary
[{"_name": "Jeffrey Lee", "_uid": "jeff", "_password": "sha256$BZW6uj8OBmWPmsYn$dbd74ce118c6677fdb6faeede33b66269b324737c1866a3791e4eb7f33ca43d6", "_classOf": "2023", "_dob": "12.27.04"}, {"_name": "Aiden Hyunh", "_uid": "win", "_password": "sha256$QqSB5Jh0Df3PVkja$3525643758936f782617d5b684df7379857995a8d83e4a781d907fa9fd2d0785", "_classOf": "2024", "_dob": "5.12.06"}, {"_name": "Quandale Dingle", "_uid": "QD420_Wrizz", "_password": "sha256$pi0DgfP2ADn4aVex$d404b0f5584d624e129650a2bcf9d3f128ab4d1ebd24245ecca39e91089d8693", "_classOf": "2025", "_dob": "1.26.54"}, {"_name": "Luke Angelini", "_uid": "luke", "_password": "sha256$pYeV2jXuCsKj7AU1$302e96d1a3971583e805b670e096ff7126fc96ca3c5f97f24324588b75f8f4b3", "_classOf": "2023", "_dob": "7.29.04"}, {"_name": "James Armstrong", "_uid": "jame", "_password": "sha256$FAQIkB2CNkLnCItv$1204c9b6d6e8d4e09d20f1db5164be059529aa2e7126315c99b00ee5c831e704", "_classOf": "2024", "_dob": "3.28.06"}]
 
Test 4, make a dictionary
[{"_name": "Jeffrey Lee", "_uid": "jeff", "_password": "sha256$BZW6uj8OBmWPmsYn$dbd74ce118c6677fdb6faeede33b66269b324737c1866a3791e4eb7f33ca43d6", "_classOf": "2023", "_dob": "12.27.04"}, {"_name": "Aiden Hyunh", "_uid": "win", "_password": "sha256$QqSB5Jh0Df3PVkja$3525643758936f782617d5b684df7379857995a8d83e4a781d907fa9fd2d0785", "_classOf": "2024", "_dob": "5.12.06"}, {"_name": "Quandale Dingle", "_uid": "QD420_Wrizz", "_password": "sha256$pi0DgfP2ADn4aVex$d404b0f5584d624e129650a2bcf9d3f128ab4d1ebd24245ecca39e91089d8693", "_classOf": "2025", "_dob": "1.26.54"}, {"_name": "Luke Angelini", "_uid": "luke", "_password": "sha256$pYeV2jXuCsKj7AU1$302e96d1a3971583e805b670e096ff7126fc96ca3c5f97f24324588b75f8f4b3", "_classOf": "2023", "_dob": "7.29.04"}, {"_name": "James Armstrong", "_uid": "jame", "_password": "sha256$FAQIkB2CNkLnCItv$1204c9b6d6e8d4e09d20f1db5164be059529aa2e7126315c99b00ee5c831e704", "_classOf": "2024", "_dob": "3.28.06"}]
# A gateway in necessary as a web server cannot communicate directly with Python.
# In this case, imports are focused on generating hash code to protect passwords.
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date
import json

# Define a User Class/Template
# -- A User represents the data we want to manage
class User:    
    # constructor of a User object, initializes the instance variables within object (self)
    def __init__(self, name, uid, password, classOf, dob):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)
        self._classOf = classOf
        self._dob = dob
        self._age = calculate_age(dob)

    def calculate_age(born):
        today = date.today()
        return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


    # a name getter method, extracts name from object
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts email from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid
    
    @property
    def password(self):
        return self._password[0:10] + "..." # because of security only show 1st characters

    # update password, this is conventional setter
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # check password parameter versus stored/encrypted password
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
        # a classOf getter method, extracts classOf from object
    @property
    def classOf(self):
        return self._classOf
    
    # a setter function, allows classOf to be updated after initial object creation
    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf

        # a dob getter method, extracts dob from object
    @property
    def dob(self):
        return self._dob
        
    # a setter function, allows dob to be updated after initial object creation
    @dob.setter
    def dob(self, dob):
        self._dob = dob
        age =calculate_age(dob)

            # a classOf getter method, extracts age from object
    @property
    def age(self):
        return self._age
    


    # output content using str(object) in human readable form, uses getter
    def __str__(self):
        return f'name: "{self.name}", id: "{self.uid}", psw: "{self.password}", classOf: "{self.classOf}", dob: "{self.dob}", age: "{self.age}"'

    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'Person(name={self._name}, uid={self._uid}, password={self._password}, classOf={self._classOf}, dob={self._dob}, age={self._age})'


# tester method to print users
def tester(users, uid, psw, classOf, dob):
    result = None
    for user in users:
        # test for match in database
        if user.uid == uid and user.is_password(psw):  # check for match
            print("* ", end="")
            result = user
        # print using __str__ method
        print(str(user))
    return result
        

# place tester code inside of special if!  This allows include without tester running
if __name__ == "__main__":

    # define user objects
    u1 = User(name='Jeffrey Lee', uid='jeff', password='123jeff', classOf='2023', dob =date(2004, 12, 27))
    u2 = User(name='Aiden Hyunh', uid='win', password='123win', classOf='2024', dob =date(2006, 5, 12))
    u3 = User(name='Jagger Klein', uid='jagg', password='123jagg', classOf='2023', dob =date(2004, 9, 18))
    u4 = User(name='Luke Angelini', uid='luke', password='123luke', classOf='2023', dob =date(2004, 7, 29))
    u5 = User(name='James Armstrong', uid='jame', password='123jame', classOf='2024', dob =date(2006, 3, 28))

    # put user objects in list for convenience
    users = [u1, u2, u3, u4, u5]

    # Find user
    print("Test 1, find user 3")
    u = tester(users, u3.uid, "123jagg", u3.classOf, u3.dob, u3.age)

    # spacing
    print(" ")
    # Change user
    print("Test 2, change user 3")
    u.name = "Quandale Dingle"
    u.uid = "QD420_Wrizz"
    u.set_password("123quandale")
    u.classOf = ("2025")
    u.dob = date(2000, 1, 26)
    u.age = (calculate_age(dob)) 
    u = tester(users, u.uid, "123quandale", u.classOf, u.dob, u.age)

    # spacing
    print(" ")

    # Make dictionary
    ''' 
    The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. 
    Every object in Python has an attribute that is denoted by __dict__. 
    Use the json.dumps() method to convert the list of Users to a JSON string.
    '''
    print("Test 3, make a dictionary")
    json_string = json.dumps([user.__dict__ for user in users]) 
    print(json_string)

    # spacing
    print(" ")

    print("Test 4, make a dictionary")
    json_string = json.dumps([vars(user) for user in users]) 
    print(json_string)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb Cell 9 in <cell line: 115>()
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=113'>114</a> # place tester code inside of special if!  This allows include without tester running
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=114'>115</a> if __name__ == "__main__":
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=115'>116</a> 
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=116'>117</a>     # define user objects
--> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=117'>118</a>     u1 = User(name='Jeffrey Lee', uid='jeff', password='123jeff', classOf='2023', dob =date(2004, 12, 27))
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=118'>119</a>     u2 = User(name='Aiden Hyunh', uid='win', password='123win', classOf='2024', dob =date(2006, 5, 12))
    <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=119'>120</a>     u3 = User(name='Jagger Klein', uid='jagg', password='123jagg', classOf='2023', dob =date(2004, 9, 18))

/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb Cell 9 in User.__init__(self, name, uid, password, classOf, dob)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=15'>16</a> self._classOf = classOf
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=16'>17</a> self._dob = dob
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/jeffrey/vscode/firstfastpages/_notebooks/2023-01-10-model-oop.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=17'>18</a> self._age = calculate_age(dob)

NameError: name 'calculate_age' is not defined

Hacks: Login Systems and Age Calculations

from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date
import json

class User:    

    def __init__(self, name, uid, password, classOf, dob):
        self._name = name    # variables with self prefix become part of the object, 
        self._uid = uid
        self.set_password(password)
        self._classOf = classOf
        self._dob = dob
    
    @property
    def name(self):
        return self._name
    
    # a setter function, allows name to be updated after initial object creation
    @name.setter
    def name(self, name):
        self._name = name
    
    # a getter method, extracts email from object
    @property
    def uid(self):
        return self._uid
    
    # a setter function, allows name to be updated after initial object creation
    @uid.setter
    def uid(self, uid):
        self._uid = uid
        
    # check if uid parameter matches user id in object, return boolean
    def is_uid(self, uid):
        return self._uid == uid

    # a classOf getter method, extracts classOf from object
    @property
    def classOf(self):
        return self._classOf
    
    # a setter function, allows classOf to be updated after initial object creation
    @classOf.setter
    def classOf(self, classOf):
        self._classOf = classOf
    
    # dob property is returned as string, to avoid unfriendly outcomes
    @property
    def dob(self):
        dob_string = self._dob.strftime('%m-%d-%Y')
        return dob_string
    
    # dob should be have verification for type date
    @dob.setter
    def dob(self, dob):
        self._dob = dob
        
    # age is calculated and returned each time it is accessed
    @property
    def age(self):
        today = date.today()
        return today.year - self._dob.year - ((today.month, today.day) < (self._dob.month, self._dob.day))
    
    # dictionary is customized, removing password for security purposes
    @property
    def dictionary(self):
        dict = {
            "name" : self.name,
            "uid" : self.uid,
            "classOf": self.classOf,
            "dob" : self.dob,
            "age" : self.age    
        }
        return dict
    
    # update password, this is conventional setter
    def set_password(self, password):
        """Create a hashed password."""
        self._password = generate_password_hash(password, method='sha256')

    # check password parameter versus stored/encrypted password
    def is_password(self, password):
        """Check against hashed password."""
        result = check_password_hash(self._password, password)
        return result
    
    # output content using json dumps, this is ready for API response
    def __str__(self):
        return json.dumps(self.dictionary)
    
    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'User(name={self._name}, uid={self._uid}, password={self._password}, classOf={self._classOf}, dob={self._dob})'
    

if __name__ == "__main__":
    u1 = User(name='Jeffrey Lee', uid='jeff', password='123jeff', classOf='2023', dob=date(2004, 12, 27))
    u2 = User(name='Aiden Hyunh', uid='win', password='123win', classOf='2024', dob=date(2006, 5, 12))
    u3 = User(name='Jagger Klein', uid='jagg', password='123jagg', classOf='2023', dob=date(2004, 9, 18))
    u4 = User(name='Luke Angelini', uid='luke', password='123luke', classOf='2023', dob=date(2004, 7, 29))
    u5 = User(name='James Armstrong', uid='jame', password='123jame', classOf='2024', dob=date(2006, 3, 28))
    print("JSON ready string:\n", u1, u2, u3, u4, u5, "\n") 
    print("Raw Variables of object:\n", vars(u1), "\n", vars(u2), "\n", vars(u3), "\n", vars(u4), "\n", vars(u5), "\n") 
    print("Raw Attributes and Methods of object:\n", dir(u1), "\n")
    print("Representation to Re-Create the object:\n", repr(u1), "\n", repr(u2), "\n", repr(u3), "\n", repr(u4), "\n", repr(u5), "\n")  
JSON ready string:
 {"name": "Jeffrey Lee", "uid": "jeff", "classOf": "2023", "dob": "12-27-2004", "age": 18} {"name": "Aiden Hyunh", "uid": "win", "classOf": "2024", "dob": "05-12-2006", "age": 16} {"name": "Jagger Klein", "uid": "jagg", "classOf": "2023", "dob": "09-18-2004", "age": 18} {"name": "Luke Angelini", "uid": "luke", "classOf": "2023", "dob": "07-29-2004", "age": 18} {"name": "James Armstrong", "uid": "jame", "classOf": "2024", "dob": "03-28-2006", "age": 16} 

Raw Variables of object:
 {'_name': 'Jeffrey Lee', '_uid': 'jeff', '_password': 'sha256$uyT7mixETVBM8xRm$bbd2f7841827d5fa5dcca45702b4eab39ca6548fe91fcd99971971c4699e8332', '_classOf': '2023', '_dob': datetime.date(2004, 12, 27)} 
 {'_name': 'Aiden Hyunh', '_uid': 'win', '_password': 'sha256$cuzQ0rw4bUiieMP4$f4901b9cd31de83afd22563693dd282b4806dd38642489bec09436c282afd84a', '_classOf': '2024', '_dob': datetime.date(2006, 5, 12)} 
 {'_name': 'Jagger Klein', '_uid': 'jagg', '_password': 'sha256$2Fz5eDQV1neQKkIn$92ea2806998b230dbb95c51115dcc9932a269a954555ce60494232bfe7428132', '_classOf': '2023', '_dob': datetime.date(2004, 9, 18)} 
 {'_name': 'Luke Angelini', '_uid': 'luke', '_password': 'sha256$O785ZgeUnVBwrHPj$57ce59c58d9858ca51531e81ebffc69346f7b6b220f14ed6ebec94d9c962f152', '_classOf': '2023', '_dob': datetime.date(2004, 7, 29)} 
 {'_name': 'James Armstrong', '_uid': 'jame', '_password': 'sha256$LplXydPQLB6cwMhA$ec5bf468c7b65d02769988fbd80e8f158d41117723a8e1221b412cb9bc6709ab', '_classOf': '2024', '_dob': datetime.date(2006, 3, 28)} 

Raw Attributes and Methods of object:
 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_classOf', '_dob', '_name', '_password', '_uid', 'age', 'classOf', 'dictionary', 'dob', 'is_password', 'is_uid', 'name', 'set_password', 'uid'] 

Representation to Re-Create the object:
 User(name=Jeffrey Lee, uid=jeff, password=sha256$uyT7mixETVBM8xRm$bbd2f7841827d5fa5dcca45702b4eab39ca6548fe91fcd99971971c4699e8332, classOf=2023, dob=2004-12-27) 
 User(name=Aiden Hyunh, uid=win, password=sha256$cuzQ0rw4bUiieMP4$f4901b9cd31de83afd22563693dd282b4806dd38642489bec09436c282afd84a, classOf=2024, dob=2006-05-12) 
 User(name=Jagger Klein, uid=jagg, password=sha256$2Fz5eDQV1neQKkIn$92ea2806998b230dbb95c51115dcc9932a269a954555ce60494232bfe7428132, classOf=2023, dob=2004-09-18) 
 User(name=Luke Angelini, uid=luke, password=sha256$O785ZgeUnVBwrHPj$57ce59c58d9858ca51531e81ebffc69346f7b6b220f14ed6ebec94d9c962f152, classOf=2023, dob=2004-07-29) 
 User(name=James Armstrong, uid=jame, password=sha256$LplXydPQLB6cwMhA$ec5bf468c7b65d02769988fbd80e8f158d41117723a8e1221b412cb9bc6709ab, classOf=2024, dob=2006-03-28) 

My Personal Design

I do eventually want to add a few more aspects to the design, including the possibility of allowing users to leave reviews of other attributes / properties. Also working on adding images, either to OOP or frontend CRUD.

from datetime import date
import json

class User:    

    def __init__(self, username, password, email):
        self._username = username    # variables with self prefix become part of the object, 
        self._password = password
        self._email = email


    # getter method for username
    @property
    def username(self):
        return self._username
    
    # setter method for username
    @username.setter
    def name(self, username):
        self._username = username
        
    # getter method for password
    @property
    def password(self):
        return self._password
    
    # setter method for password
    @password.setter
    def name(self, password):
        self._password = password
  
    # getter method for email
    @property
    def email(self):
        return self._email
    
    # setter method for email
    @email.setter
    def email(self, email):
        self._email = email
    
    # dictionary is customized, removing password for security purposes
    @property
    def dictionary(self):
        dict = {
            "username" : self.username,
            "email" : self.email,
        }
        return dict
  
    # output content using json dumps, this is ready for API response
    def __str__(self):
        return json.dumps(self.dictionary)
    
    # output command to recreate the object, uses attribute directly
    def __repr__(self):
        return f'User(username={self._username}, password={self._password},email={self._email})'
    

if __name__ == "__main__":
    
    u1 = User(username='jeffrey_the_gerbil', password='Jeff1227', email = 'leejeffreysc@gmail.com')
    
    print("JSON ready string:\n", u1, "\n") 
    print("Raw Variables of object:\n", vars(u1), "\n") 
    print("Raw Attributes and Methods of object:\n", dir(u1), "\n")
    print("Representation to Re-Create the object:\n", repr(u1), "\n") 
    
JSON ready string:
 {"username": "jeffrey_the_gerbil", "email": "leejeffreysc@gmail.com"} 

Raw Variables of object:
 {'_username': 'jeffrey_the_gerbil', '_password': 'Jeff1227', '_email': 'leejeffreysc@gmail.com'} 

Raw Attributes and Methods of object:
 ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_email', '_password', '_username', 'dictionary', 'email', 'name', 'password', 'username'] 

Representation to Re-Create the object:
 User(username=jeffrey_the_gerbil, password=Jeff1227,email=leejeffreysc@gmail.com)