Advanced Classes
Class Initialization¶
A class can be set up to accept arguments to set up some basic attributes and other things set up when it is created. This is done by using the __init__ class function and passing self followed by any arguments that you want to require for the class. Let’s set up our person to now take age as an argument.
#Using __init__ let's us set up an initialization
#We pass it arguments and then we can use those to set attributes or properties
#Here we pass an age attribute and give it to our class object
class Person:
def __init__(self, age):
self.age = age
def say_hi(self):
print("Hi")
def tell_age(self):
print("I am {} years old.".format(self.age))
When we create a class instance, we have to pass in the age for it work.
#Now Carl is 25 years old
Carl = Person(25)
Carl.tell_age()
What about doing age in terms of number of days? We can do that too by dividing by 365 from the days.
class Person:
def __init__(self, days):
self.age = days / 365
def say_hi(self):
print("Hi")
def tell_age(self):
print("I am {} years old.".format(self.age))
carl = Person(10000)
carl.tell_age()
One problem is that we do not know if we are going to get the correct input. A good practice would be to force the type to be something like, say integer. Let's switch it back to the way from before and ensure that if we give it a string "fish" that it will fail.
class Person:
def __init__(self, age):
assert type(age) == int, "Age must be an integer"
self.age = age
def say_hi(self):
print("Hi")
def tell_age(self):
print("I am {} years old.".format(self.age))
#This will fail
carl = Person("Fish")
carl.tell_age()
#This will work
carl = Person(25)
carl.tell_age()
What about a name for our person? We will do the same as before.
class Person:
def __init__(self, age, name):
assert type(age) == int, "Age must be an integer"
assert type(name) == str, "Name must be a string"
self.age = age
self.name = name
def say_hi(self):
print("Hi")
def tell_age(self):
print("I am {} years old.".format(self.age))
carl = Person(25, "Carl")
carl.tell_age()
In case someone has a birthday, or they entered the wrong age, the ability to set the age would be useful. Let's also add this function.
class Person:
def __init__(self, age, name):
assert type(age) == int, "Age must be an integer"
assert type(name) == str, "Name must be a string"
self.age = age
self.name = name
def say_hi(self):
print("Hi")
def tell_age(self):
print("I am {} years old.".format(self.age))
def set_age(self, age):
assert type(age) == int, "Age must be an integer"
self.age = age
#Create person
carl = Person(25, "Carl")
#Get the age
carl.tell_age()
#Change the age
carl.set_age(26)
#Get the age again
carl.tell_age()