Jump to content
Sign in to follow this  
dil_bert

a class for storing contact data -

Recommended Posts

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",
    "joe.doe@example.com"
)

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.