This is the last class of the introductory part of python, then we'll explore the intermediate level where libraries such as numpy and matplotlib.
That is why this topic is so important, it gathers together all the previous concepts and tools.
As we have mentioned during the class, python is a object oriented based language and today we will understand what does it mean.
The missing structure is called classes
class animal:
def __init__(self,name,age,specie):
self.name=name
self.age=age
self.spe=specie
animalito=animal('Comino',2,'Dog')
animalito.spe
'Dog'
A=animal('Scooby',2,'Dog')
A.age=3
A.age
3
Zoo=[]
animals=['Dog','Cat','Mouse']
names=['Scooby','Tom','Jerry']
for i in range(len(animals)):
Zoo.append(animal(names[i],1,animals[i]))
print(Zoo)
[<__main__.animal object at 0x1040846a0>, <__main__.animal object at 0x1040846d8>, <__main__.animal object at 0x104084710>]
Take a look at this structure
print(Zoo[0])
<__main__.animal object at 0x1040846a0>
What do you think it means?
We saved there a
DognamedScoobyand 1 year old!,
But, What if....
print(Zoo[0].name,Zoo[0].spe,Zoo[0].age)
Scooby Dog 1
Let us construct a different example.
We are going to work on a problem we already did, Let us create ourselves!
Lets have a student class.
import random
random.seed(10987654321012345678910)
class student:
def __init__(self,name,age,career,semester):
self.name=name
self.age=age
self.career=career
self.semester=semester
def Grade(self):
return round(random.random()*5,1)
Me=student('Mauricio',80,'Professor',1)
Me.Grade()
2.2
Me.Grade()
0.0
Me.Grade()
3.5
Let us create a more complex class
class animal2:
"This class helps you to create an animal"
def __init__(self,name,age,specie,talk):
self.name=name
self.age=age
self.spe=specie
self.speech=talk
def talk(self):
return self.speech
def sit(self):
if(self.spe=='Dog'):
return 'Sitted!'
else:
return'Nee'
Zoo2=[]
animals=['Dog','Cat','Mouse']
names=['Scooby','Tom','Jerry']
ages=[1,2,3]
speeches=['Woof','Miau!','Cheese!']
for i in range(len(animals)):
Zoo2.append(animal2(names[i],1,animals[i],speeches[i]))
print(Zoo2[-1].talk())
Cheese!
print(Zoo2[2].name)
Jerry
print(Zoo2[2].sit())
Nee
print(Zoo2[1].talk())
Miau!
?animal2
Let see some examples of what does inheritance means while programming.
For example, my family as a class
class Sevilla:
def __init__(self,name,age):
self.name=name
self.age=age
def hair(self):
return 'Black' #We all have black hair
def eyes(self):
return 'Brown' #We all have Brown eyes
def LastName(self):
return 'Sevilla' #We all have the same last name
If someday i have a son/daughter, for sure he/she will have some features I do, so
class SonDaugther(Sevilla):
def __init__(self,name):
self.na=name
Me=Sevilla('Mauricio',80)
MySon=SonDaugther('son')
print(MySon.na)
son
print(MySon.hair())
Black
print(MySon.eyes())
Brown
print(MySon.LastName())
Sevilla
class SonDaugther2(Sevilla):
def __init__(self,name):
Sevilla.__init__(self,'Nombre',10)
self.na=name
MySon2=SonDaugther2('name')
MySon2.age
10