Join 36000+ teachers and students using TTIO.
A class is a kind of data type, just like a string, integer or list. When we create an object of that data type, we call it an instance of a class. The data values which we store inside an object are called attributes, and the functions which are associated with the object are called methods.
Here is an example of a simple custom class which stores information about a person. Note the attributes (name, surname, birthdate) and the methods (in this case the method "age")
import datetime # we will use this for date objects
class Person:
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(
"Jane",
"Doe",
datetime.date(1992, 3, 12), # year, month, day
"No. 12 Short Street, Greenville",
"555 456 0987",
"[email protected]"
)
print(person.name)
print(person.email)
print(person.age())
The examples above are classes and objects in their simplest form, and are not really useful in real life applications. To understand the meaning of classes we have to understand the built-in __init__() function. All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__()
function is called automatically every time the class is being used to create a new object.
www.teachyourselfpython.com