Python Forum

Full Version: a contact book - a class made to store data
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello dear Community, 


a class for storing contact data - Here is the code of a simple custom class which stores information about a person:

import datetime # so we will use this for date objects

class Person: # this is it - this is the class 

    def __init__(self, name, surname, birthdate, address, telephone, email):
        self.name = name
        self.surname = surname
        self.birthdate = birthdate

        self.address = address
        self.telephone = telephone
        self.email = email

    def age(self):
        today = datetime.date.today()
        age = today.year - self.birthdate.year

        if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day):
            age -= 1

        return age

person = Person(
    "Joe",
    "Doe",
    datetime.date(1952, 4, 22), # year, month, day
    "No. 1444 Short Street, Munich",
    "555 4564444444444444 0987",
    "[email protected]"
)

print(person.name)
print(person.email)
print(person.age())
i want to store the data in a database. 


background: We start the class definition with the class keyword, followed by the class name and a colon. i think it is not bad to list any parent classes in between round brackets before the colon, but this class doesn’t have any, so i can leave them out. Inside the class body, we ve got  two functions – these are our object’s methods.

1. The first method: is called __init__, which is a special method. When we call the class object, a new instance of the class is created, and the __init__ method on this new object is immediately executed with all the parameters that we passed to the class object. The purpose of this method is thus to set up a new object using data that we have provided.

The second method is a custom method which calculates the age of our person using the birthdate and the current date.

i want to store the data in a db or in a file
If you don't have any specific requirements, then sqlalchemy is a pretty good library: https://docs.sqlalchemy.org/en/13/orm/tutorial.html
good day dear nilamo,

many thanks for the quick rely with your tipp. I will look at this library.
....and besides this i will have a closer look at peewee. 



have a great day

have a great day Smile