Learning python - part 2 - chapter 6
-
Upload
koosha-zarei -
Category
Software
-
view
113 -
download
7
description
Transcript of Learning python - part 2 - chapter 6
Learning PythonPart 2 | Winter 2014 | Koosha Zarei | QIAU
Part 2Chapter 6 – Classes & Objects
3February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
In Python, every piece of data you see or come into contact with is represented by an object.
Each of these objects has three components: an identity, a type, and a value.
4February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
The identity represents the location of the object being held in your memory.
While its type tells us what types of data and values it can have.
The value, meanwhile, can be changed in an object, but only if it is set as a mutable type.
if it is set as immutable, then it may not change.
5February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Integers, strings, lists, and so forth are all nothing more than objects.
A class allows you to define and encapsulate a group of objects into one convenient space.
Class will enable you to think of entire objects that contain both data and functions.
Objects and Classes
6February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
>>> omelet_type = “Cheese”
>>> omelet_type.lower()‘cheese’>>> omelet_type.upper()‘CHEESE’
Objects and Classes
7February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Also available are methods built into tuple, list, and dictionary objects, like the keys method of Dictionaries.
>>> fridge = {“cheese”:1, “tomato”:2, “milk”:4}>>> for x in fridge.keys():
print(x)
[‘tomato’, ‘cheese’, ‘milk’]
Objects and Classes
8February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
When you want to find out more about what is available in an object, Python exposes everything that exists in an object when you use the dir function
dir(fridge)[‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__doc__’,‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’,‘__gt__’, ‘__hash__’, ‘__init__’, ‘__iter__’, ‘__le__’, ‘__len__’,‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’,‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘items’, ‘keys’, ‘pop’, ‘popitem’,‘setdefault’, ‘update’, ‘values’]
Objects and Classes
9February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
When you have an object, you want to be able to use it naturally. For instance, once you’ve defined it, the Testclass class could produce objects that behave in a way that would feel natural when you read the source code.
10February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
In other words, when you create an object that models something from the real world, you can form your program’s objects and classes so they help the pieces of the program work in a way that someone familiar with the real-life object will recognize and be able to understand.
11February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
Python employs the concept of creating an entire class of code that acts as a placeholder.
The definition of a class is simple and mainly involves the use of the special word class along with a name.
12February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
class Fridge:“””This class implements a fridge where ingredients can be added and removed individually, or ingroups.”””
13February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
>>> f.items = {}>>> f.items[“mystery meat”] = 1
14February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
class Fridge:
def __init__(self, items={}):“””Optionally pass in an initial dictionary of items”””
if type(items) != type({}):raise TypeError(“Fridge requires a dictionary but was given %s” % type(items))
self.items = itemsreturn
15February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
When Python creates your object, the __init__ method is what passes the object its first parameter. The (self) portion is actually a variable used to represent the instance of the object.
16February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
For the Fridge class, it’s common to have a method that can operate on a group of data, and another method that works with just a single element.
17February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
Whenever you have this situation, you can save your effort by mak invoke the method that works on any number of items. In fact, sometimes it’s useful to have this method be considered private, or not a part of the interface.
This way it can be used or not used and changed without affecting how the class is used, because any changes you make will not be seen outside an object, only inside.
18February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
class Fridge:
# the docstringdef __add_multi(self, food_name, quantity):
# the docstring
if (not food_name in self.items):self.items[food_name] = 0
self.items[food_name] = self.items[food_name] + quantity
19February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
Now you have a way of adding any number of single food items to a Fridge object.
Now the add_one and the add_many methods can both be written to use it instead of you having to write similar functions two times.
20February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def add_one(self, food_name):
#docstring
if type(food_name) != type(“”):raise TypeError, “add_one requires a string, given a %s” % type(food_name)
else:self.__add_multi(food_name, 1)
return True
21February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def add_many(self, food_dict):
if type(food_dict) != type({}):raise TypeError(“add_many requires a dictionary, got a %s” %food_dict)
for item in food_dict.keys():self.__add_multi(item, food_dict[item])
return
22February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
add_one and add_many each serve similar purposes, and each one has the code to ensure that it is being used appropriately. At the same time, they both use __add_multi to actually do the heavy lifting. If anything changes regarding how your class works inside of __add_multi, you will save time because it will change how both of these methods behave.
23February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
>>> f = Fridge({“eggs”:6, “milk”:4, “cheese”:3})>>> f.items{‘cheese’: 3, ‘eggs’: 6, ‘milk’: 4}>>> f.add_one(“grape”)True>>> f.items{‘cheese’: 3, ‘eggs’: 6, ‘grape’: 1, ‘milk’: 4}>>> f.add_many({“mushroom”:5, “tomato”:3})>>> f.items{‘tomato’: 3, ‘cheese’: 3, ‘grape’: 1, ‘mushroom’: 5, ‘eggs’: 6, ‘milk’: 4}
24February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
We will want to add are the methods that enable you to determine whether something is in the Fridge.
25February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def has_various(self, foods):
try:for food in foods.keys():
if self.items[food] < foods[food]:return False
return True
except KeyError:return False
26February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def has(self, food_name, quantity=1):
return self.has_various( {food_name:quantity} )
27February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
>>> f = Fridge({“eggs”:6, “milk”:4, “cheese”:3})>>> if f.has(“cheese”, 2):… print(“It’s time to make an omelet!”)...
It’s time to make an omelet!
28February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classesdef __get_multi(self, food_name, quantity):
try:if (self.items[food_name] is None):
return False;
if (quantity > self.items[food_name]):return False;
self.items[food_name] = self.items[food_name] - quantityexcept KeyError:
return False
return quantity
29February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def get_one(self, food_name):
if type(food_name) != type(“”):raise TypeError(“get_one requires a string, given a %s” %type(food_name))
else:result = self.__get_multi(food_name, 1)
return result
30February 2014Learning Python | Part 2- Chapter 5 | Koosha Zarei
Objects and Classes
def get_many(self, food_dict):
if self.has_various(food_dict):foods_removed = {}
for item in food_dict.keys():foods_removed[item] = self.__get_multi(item, food_dict[item])
return foods_removed