1. A class is a software entity that has ...
3. The process of creating multiple objects of (or based on) a class is called:
4. You could create a class called 'Person'. In this example, note that any given person has a name, and can 'do' things like "speak" and "walk". Speaking and walking are examples of ...
5. Here is a simple custom class which stores information about a person. Name two attributes that have been defined in this class.
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())
age,date
person, class
name, surname
Jane,datetime
6. Inside the class body, we define two functions - these are our object's methods. The first is called __init__, which is a special method. The purpose of this method is:
7. What is the age method (starting on line 14) doing?
8. You may have noticed that both method definitions have "self" as the first parameter, and we use this variable inside the method bodies but we don't appear to pass this parameter in (e.g on Line 35) Why?
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(
"Joe",
"Bloggs",
datetime.date(1992, 3, 12), # year, month, day
"No. 10 Python Street",
"555 456 0987",
"[email protected] "
)
print(person.name)
print(person.email)
print(person.age())
because self refers to python itself, and python knows!
because 'self' is a variable that has been set to 'self' in the__init__ method
because whenever we call a method on an object, the object itself is automatically passed in as the first parameter
That is incorrect, Line 35 should read: print(person.age(self))
9. What is happening on lines 7 and 8?
10. Line 11 is creating a new instance of the class Person. Is there an error?