FF - Object Oriented Programming
FF - Object Oriented Programming
● For now, we can think to objects as the initialization of a custom data type that
someone have defined previously
● The big novel: Everything in Python is an object and you already used
objects in our previous exercises !
● Class ● Object
○ What is the concept? ○ Concrete instance that we can
○ How does it work? use
○ How is it build? ○ It is built depending on the
rules that its class defines
class Product: Py
def __init__(self, name,price,number):
self._name = name # attribute self: special keyword that
self._price = price # attribute say to interpreter that
self._number = number # attribute methods or attributes value
have to be assigned to each
def get_name(self): #method object that is built from this
return self._name class !
def get_price(self): #method
return self._price
def set_price(self,new_price): #method
self._price=new_price
def main():
p = Product("pen",1.50,200) #Instantiation of an object p (Product type)
print(p.get_name()) #call of a method on object P
print(p.get_price())
p.set_price(2.00)
print(p.get_price())
main()
class Product: Py
def __init__(self, name,price,number):
self._name = name # attribute
self._price = price # attribute
self._number = number # attribute
Py
n=0
products_list=[]
while n<10:
request = input(“Insert product,price,quantity”)
fields= request.split(“,”)
p = Product(fields[0],float(fields[1]),float(fields[2]))
products_list.append(p)
n+=1
for item in products_list:
p.set_price(p.get_price()+2)
p.buy() # this method could reduce the number of available items ! Has to be defined in the class
class Product: Py
……..
def get_name(self): #method
return self._name
def get_price(self): #method
return self._price
def set_price(self,new_price): #method
self._price=new_price
def buy(self):
if self._number >0 :
self._number-=1
● Read registry.txt, create an object for each person and add to a list
● Compute the average age in the registry by defining an apposite function