id
int64
0
25.6k
text
stringlengths
0
4.59k
3,100
let' write some code to see what happens when you not use any error handling mechanism in your program number int(input('please enter the number between ')print('you have entered number',numberabove programme will work correctly as long as the user enters numberbut what happens if the users try to puts some other data type(like string or listplease enter the number between 'hitraceback (most recent call last)file " :/python/python /exception py"line in number int(input('please enter the number between ')valueerrorinvalid literal for int(with base "'hi'now valueerror is an exception type let' try to rewrite the above code with exception handling import sys print('previous code with exception handling'trynumber int(input('enter number between ')except(valueerror)print('error numbers only'sys exit(print('you have entered number',numberif we run the programand enter string (instead of number)we can see that we get different result previous code with exception handling enter number between 'hierror numbers only
3,101
raising exceptions to raise your exceptions from your own methods you need to use raise keyword like this raise exceptionclass('some text here'let' take an example def enterage(age)if age< raise valueerror('only positive integers are allowed'if age == print('entered age is even'elseprint('entered age is odd'trynum int(input('enter your age')enterage(numexcept valueerrorprint('only positive integers are allowed'run the program and enter positive integer expected output enter your age entered age is even but when we try to enter negative number we getexpected output enter your age- only positive integers are allowed
3,102
creating custom exception class you can create custom exception class by extending baseexception class or subclass of baseexception from above diagram we can see most of the exception classes in python extends from the baseexception class you can derive your own exception class from baseexception class or from its subclass create new file called negativenumberexception py and write the following code class negativenumberexception(runtimeerror)def __init__(selfage)super(__init__(self age age above code creates new exception class named negativenumberexceptionwhich consists of only constructor which call parent class constructor using super()__init__(and sets the age
3,103
now to create your own custom exception classwill write some code and import the new exception class from negativenumberexception import negativenumberexception def enterage(age)if age raise negativenumberexception('only positive integers are allowed'if age = print('age is even'elseprint('age is odd'trynum int(input('enter your age')enterage(numexcept negativenumberexceptionprint('only positive integers are allowed'exceptprint('something is wrong'outputenter your age- only positive integers are allowed another way to create custom exception class class customexception(exception)def __init__(selfvalue)self parameter value def __str__(self)return repr(self parametertryraise customexception('my useful error message!'except customexception as instanceprint('caughtinstance parameter
3,104
output caughtmy useful error messageexception hierarchy the class hierarchy for built-in exceptions isbaseexception +-systemexit +-keyboardinterrupt +-generatorexit +-exception +-stopiteration +-stopasynciteration +-arithmeticerror +-floatingpointerror +-overflowerror +-zerodivisionerror +-assertionerror +-attributeerror +-buffererror +-eoferror +-importerror +-lookuperror +-indexerror +-keyerror +-memoryerror +-nameerror +-unboundlocalerror +-oserror +-blockingioerror +-childprocesserror +-connectionerror +-brokenpipeerror +-connectionabortederror +-connectionrefusederror +-connectionreseterror +-fileexistserror +-filenotfounderror +-interruptederror +-isadirectoryerror +-notadirectoryerror +-permissionerror +-processlookuperror +-timeouterror +-referenceerror +-runtimeerror +-notimplementederror +-recursionerror +-syntaxerror +-indentationerror
3,105
+-taberror +-systemerror +-typeerror +-valueerror +-unicodeerror +-unicodedecodeerror +-unicodeencodeerror +-unicodetranslateerror +-warning +-deprecationwarning +-pendingdeprecationwarning +-runtimewarning +-syntaxwarning +-userwarning +-futurewarning +-importwarning +-unicodewarning +-byteswarning +-resourcewarning
3,106
oop in python object serialization in the context of data storageserialization is the process of translating data structures or object state into format that can be stored (for examplein file or memory bufferor transmitted and reconstructed later in serializationan object is transformed into format that can be storedso as to be able to deserialize it later and recreate the original object from the serialized format pickle pickling is the process whereby python object hierarchy is converted into byte stream (usually not human readableto be written to filethis is also known as serialization unpickling is the reverse operationwhereby byte stream is converted back into working python object hierarchy pickle is operationally simplest way to store the object the python pickle module is an object-oriented way to store objects directly in special storage format what can it dopickle can store and reproduce dictionaries and lists very easily stores object attributes and restores them back to the same state what pickle can' doit does not save an objects code only it' attributes values it cannot store file handles or connection sockets in short we can saypickling is way to store and retrieve data variables into and out from files where variables can be listsclassesetc to pickle something you mustimport pickle write variable to filesomething like pickle dump(mystringoutfileprotocol)where rd argument protocol is optional to unpickling something you mustimport pickle write variable to filesomething like mystring pickle load(inputfile
3,107
methods the pickle interface provides four different methods dump(the dump(method serializes to an open file (file-like objectdumps()serializes to string load()deserializes from an open-like object loads(deserializes from string based on above procedurebelow is an example of "picklingoutput my cat pussy is white and has legs would you like to see her pickledhere she isb'\ \ c__main__\ncat\nq\ )\ \ } \ ( \ \ \ \ number_of_legs \ \ \ \ \ \ colorq\ \ \ \ \ whiteq\ ub soin the example abovewe have created an instance of cat class and then we've pickled ittransforming our "catinstance into simple array of bytes this way we can easily store the bytes array on binary file or in database field and restore it back to its original form from our storage support in later time also if you want to create file with pickled objectyou can use the dump(method instead of the dumps*()onepassing also an opened binary file and the pickling result will be stored in the file automatically binary_file open(my_pickled_pussy bin'mode='wb'my_pickled_pussy pickle dump(pussybinary_filebinary_file close(
3,108
unpickling the process that takes binary array and converts it to an object hierarchy is called unpickling the unpickling process is done by using the load(function of the pickle module and returns complete object hierarchy from simple bytes array let' use the load function in our previous example output meow is black pussy is white json json(javascript object notationhas been part of the python standard library is lightweight data-interchange format it is easy for humans to read and write it is easy to parse and generate because of its simplicityjson is way by which we store and exchange datawhich is accomplished through its json syntaxand is used in many web applications as it is in human readable formatand this may be one of the reasons for using it in data transmissionin addition to its effectiveness when working with apis an example of json-formatted data is as follow{"employid" "name""zack""age": "isemployed"truepython makes it simple to work with json files the module sused for this purpose is the json module this module should be included (built-inwithin your python installation so let' see how can we convert python dictionary to json and write it to text file
3,109
json to python reading json means converting json into python value (objectthe json library parses json into dictionary or list in python in order to do thatwe use the loads(function (load from string)as followoutput below is one sample json filedata json {"menu""id""file""value""file""popup""menuitem"{"value""new""onclick""createnewdoc()"}{"value""open""onclick""opendoc()"}{"value""close""onclick""closedoc()"}above content (data jsonlooks like conventional dictionary we can use pickle to store this file but the output of it is not human readable form json(java script object notificationis very simple format and that' one of the reason for its popularity now let' look into json output through below program
3,110
output above we open the json file (data jsonfor readingobtain the file handler and pass on to json load and getting back the object when we try to print the output of the objectits same as the json file although the type of the object is dictionaryit comes out as python object writing to the json is simple as we saw this pickle above we load the json fileadd another key value pair and writing it back to the same json file now if we see out data jsonit looks different not in the same format as we see previously to make our output looks same (human readable format)add the couple of arguments into our last line of the programjson dump(conffhindent= separators (',''')similarly like picklewe can print the string with dumps and load with loads below is an example of that
3,111
yaml yaml may be the most human friendly data serialization standard for all programming languages python yaml module is called pyaml yaml is an alternative to jsonhuman readable codeyaml is the most human readable format so much so that even its front-page content is displayed in yaml to make this point compact codein yaml we use whitespace indentation to denote structure not brackets syntax for relational datafor internal references we use anchors (&and aliases (*one of the area where it is used widely is for viewing/editing of data structuresfor example configuration filesdumping during debugging and document headers installing yaml as yaml is not built-in modulewe need to install it manually best way to install yaml on windows machine is through pip run below command on your windows terminal to install yamlpip install pyaml (windows machinesudo pip install pyaml (*nix and macon running above commandscreen will display something like below based on what' the current latest version collecting pyaml
3,112
using cached pyaml--py py -none-any whl collecting pyyaml (from pyamlusing cached pyyaml- tar gz installing collected packagespyyamlpyaml running setup py install for pyyaml done successfully installed pyyaml- pyamlto test itgo to the python shell and import the yaml moduleimport yamlif no error is foundthen we can say installation is successful after installing pyamllet' look at below codescript_yaml py above we created three different data structuredictionarylist and tuple on each of the structurewe do yaml dump important point is how the output is displayed on the screen output
3,113
dictionary output looks clean ie keyvalue white space to separate different objects list is notated with dash (-tuple is indicated first with !!python/tuple and then in the same format as lists loading yaml file so let' say have one yaml filewhich contains--an employee record nameraagvendra joshi jobdeveloper skilloracle employedtrue foodsapple orange strawberry mango languagesoracleelite power_builderelite full stack developerlame education gcses -levels mca in something called com now let' write code to load this yaml file through yaml load function below is code for the same
3,114
as the output doesn' looks that much readablei prettify it by using json in the end compare the output we got and the actual yaml file we have output
3,115
one of the most important aspect of software development is debugging in this section we'll see different ways of python debugging either with built-in debugger or third party debuggers pdb the python debugger the module pdb supports setting breakpoints breakpoint is an intentional pause of the programwhere you can get more information about the programs state to set breakpointinsert the line pdb set_trace(example pdb_example py import pdb = = pdb set_trace(total pdb set_trace(we have inserted few breakpoints in this program the program will pause at each breakpoint (pdb set_trace()to view variables contents simply type the variable name :\python\python >python pdb_example py :\python\python \pdb_example py( )(-total (pdbx (pdby (pdbtotal **nameerrorname 'totalis not defined (pdbpress or continue to go on with the programs execution until the next breakpoint (pdbc --return- :\python\python \pdb_example py( )()->none -total (pdbtotal
3,116
eventuallyyou will need to debug much bigger programs programs that use subroutines and sometimesthe problem that you're trying to find will lie inside subroutine consider the following program import pdb def squar(xy)out_squared ^ ^ return out_squared if __name__ ="__main__"#pdb set_trace(print (squar( )now on running the above programc:\python\python >python pdb_example py :\python\python \pdb_example py( )(-print (squar( )(pdbwe can use to get helpbut the arrow indicates the line that' about to be executed at this point it' helpful to hit to to step into that line (pdbs --call- :\python\python \pdb_example py( )squar(-def squar(xy)this is call to function if you want an overview of where you are in your codetry (pdbl import pdb def squar(xy)-out_squared ^ ^ return out_squared if __name__ ="__main__" pdb set_trace( print (squar( )[eof
3,117
(pdbyou can hit to advance to the next line at this point you are inside the out_squared method and you have access to the variable declared inside the function and (pdbx (pdby (pdbx^ (pdby^ (pdbx** (pdby** (pdbso we can see the operator is not what we wanted instead we need to use *operator to do squares this way we can debug our program inside the functions/methods logging the logging module has been part of python' standard library since python version as it' built-in module all python module can participate in loggingso that our application log can include your own message integrated with messages from third party module it provides lot of flexibility and functionality benefits of logging diagnostic loggingit records events related to the application' operation audit loggingit records events for business analysis messages are written and logged at levels of "severity"debug (debug())diagnostic messages for development info (info())standard "progressmessages warning (warning())detected non-serious issue error (error())encountered an errorpossibly serious critical (critical())usually fatal error (program stopslet' looks into below simple programlogging py
3,118
import logging logging basicconfig(level=logging infologging debug('this message will be ignored'this will not print logging info('this should be logged'it'll print logging warning('and thistoo'it'll print above we are logging messages on severity level first we import the modulecall basicconfig and set the logging level level we set above is info then we have three different statementdebug statementinfo statement and warning statement output of logging py info:root:this should be logged warning:root:and thistoo as the info statement is below debug statementwe are not able to see the debug message to get the debug statement too in the output terminalall we need to change is the basicconfig level logging basicconfig(level=logging debugand in the output we can seedebug:root:this message will be ignored info:root:this should be logged warning:root:and thistoo also the default behavior means if we don' set any logging level is warning just comment out the second line from the above program and run the code #logging basicconfig(level=logging debugoutput warning:root:and thistoo python built in logging level are actually integers import logging logging debug logging critical
3,119
logging warning logging info logging error we can also save the log messages into the file logging basicconfig(level=logging debugfilename 'logging log'now all log messages will go the file (logging login your current working directory instead of the screen this is much better approach as it lets us to do post analysis of the messages we got we can also set the date stamp with our log message logging basicconfig(level=logging debugformat '%(asctime) %(levelname) :%(message) 'output will get something like : : , debug:this message will be ignored : : , info:this should be logged : : , warning:and thistoo benchmarking benchmarking or profiling is basically to test how fast is your code executes and where the bottlenecks arethe main reason to do this is for optimization timeit python comes with in-built module called timeit you can use it to time small code snippets the timeit module uses platform-specific time functions so that you will get the most accurate timings possible soit allows us to compare two shipment of code taken by each and then optimize the scripts to given better performance the timeit module has command line interfacebut it can also be imported there are two ways to call script let' use the script firstfor that run the below code and see the output import timeit
3,120
print 'by index'timeit timeit(stmt "mydict[' ']"setup="mydict {' ': ' ': ' ': }"number )print 'by get'timeit timeit(stmt 'mydict get(" ")'setup 'mydict {" ": " ": " ": }'number )output by indexby get above we use two different method by subscript and get to access the dictionary key value we execute statement million times as it executes too fast for very small data now we can see the index access much faster as compared to the get we can run the code multiply times and there will be slight variation in the time execution to get the better understanding another way is to run the above test in the command line let' do itc:\python\python >python - timeit - - "mydict {' ' ' ': ' ': }"mydict[' '] loopsbest of usec per loop :\python\python >python - timeit - - "mydict {' ' ' ': ' ': }"mydict get(' ') loopsbest of usec per loop above output may vary based on your system hardware and what all applications are running currently in your system below we can use the timeit moduleif we want to call to function as we can add multiple statement inside the function to test import timeit def testme(this_dictkey)return this_dict[keyprint (timeit timeit("testme(mydictkey)"setup ="from __main__ import testmemydict {' ': ' ': ' ': }key=' '"number= )output
3,121
3,122
oop in python python libraries requestspython requests module requests is python module which is an elegant and simple http library for python with this you can send all kinds of http requests with this library we can add headersform datamultipart files and parameters and access the response data as requests is not built-in moduleso we need to install it first you can install it by running the following command in the terminalpip install requests once you have installed the moduleyou can verify if the installation is successful by typing below command in the python shell import requests if the installation has been successfulyou won' see any error message making get request as means of example we'll be using the "pokeapi
3,123
outputmaking post requests the requests library methods for all of the http verbs currently in use if you wanted to make simple post request to an api endpoint then you can do that like soreq requests post('this would work in exactly the same fashion as our previous get requesthowever it features two additional keyword parametersdata which can be populated with say dictionarya file or bytes that will be passed in the http body of our post request json which can be populated with json object that will be passed in the body of our http request also pandaspython library pandas pandas is an open-source python library providing high-performance data manipulation and analysis tool using its powerful data structures pandas is one of the most widely used python libraries in data science it is mainly used for data mungingand with good reasonpowerful and flexible group of functionality built on numpy package and the key data structure is called the dataframe these dataframes allows us to store and manipulate tabular data in rows of observations and columns of variables there are several ways to create dataframe one way is to use dictionary for example
3,124
outputfrom the output we can see new brics dataframepandas has assigned key for each country as the numerical values through if instead of giving indexing values from to we would like to have different index valuessay the two letter country codeyou can do that easily as welladding below one lines in the above codegives brics index ['br''ru''in''ch''sa'output indexing dataframes
3,125
output pygame pygame is the open source and cross-platform library that is for making multimedia applications including games it includes computer graphics and sound libraries designed to be used with the python programming language you can develop many cool games with pygame overview pygame is composed of various moduleseach dealing with specific set of tasks for examplethe display module deals with the display window and screenthe draw module provides functions to draw shapes and the key module works with the keyboard these are just some of the modules of the library the home of the pygame library is at to make pygame applicationyou follow these steps
3,126
import the pygame library import pygame initialize the pygame library pygame init(create window screen pygame display set_mode(( , )pygame display set_caption('first pygame game'initialize game objects in this step we load imagesload soundsdo object positioningset up some state variablesetc start the game loop it is just loop where we continuously handle eventschecks for inputmove objectsand draw them each iteration of the loop is called frame
3,127
3,128
programming paradigms before diving deep into the concept of object oriented programminglet' talk little about all the programming paradigms which exist in this world procedural objectural modulesdata structures and procedures that operate upon them objects which encapsulate state and behavior and messages passed between theses objects functions and closuresrecursionlistsfunctional
3,129
programming paradigms python is multiparadigm programming language it allows the programmer to choose the paradigm that best suits the problem it allows the program to mix paradigms it allows the program to evolve switching paradigm if necessary
3,130
what is an objecta software item that contains variables and methods encapsulation dividing the code into public interfaceand private implementation of that interface object oriented design focuses on :polymorphism inheritance the ability to overload standard operators so that they have appropriate behavior based on their context the ability to create subclasses that contain specializations of their parents
3,131
what is classclasses(in classic oodefine what is common for whole class of objectse "snowy is dogcan be translated to "the snowy object is an instance of the dog class define once how dog works and then reuse it for all dogs classes correspond to variable typesthey are type objectsat the simplest levelclasses are simply namespaces dog snowy
3,132
have class
3,133
python classes class is python object with several characteristicsyou can call class as it where function and this call returns new instance of the class class has arbitrary named attributes that can be boundunbound an referenced the class attributes can be descriptors (including functionsor normal data objects class attributes bound to functions are also known as methods method can have special python-defined meaning (they're named with two leading and trailing underscoresa class can inherit from other classesmeaning it delegates to other classes the look-up of attributes that are not found in the class itself
3,134
python classes in detail (iall classes are derived from object (new-style classesclass dog(object)pass python objects have data and function attributes (methodsclass dog(object)def bark(self)print "wuff!snowy dog(snowy bark(first argument (selfis bound to this dog instance snowy added attribute to snowy
3,135
python classes in detail (iialways define your data attributes in __init__ class dataset(object)def __init__(self)self data none def store_data(selfraw_data)process the data self data processed_data class attributes are shared across all instances class platypus(mammal)latin_name "ornithorhynchus anatinus
3,136
python classes in detail (iiiuse super to call method from superclass class dataset(object)def __init__(selfdata=none)self data data class mridataset(dataset)def __init__(selfdata=noneparameters=none)here has the same effect as calling dataset __init__(selfsuper(mridatasetself__init__(dataself parameters parameters mri_data mridataset(data=[ , , ]
3,137
python classes in detail (ivspecial methods start and end with two underscores and customize standard python behavior ( operator overloadingclass my vector(object)def __init__(selfxy)self self def __add__(selfother)return my vector(self +other xself +other yv my vector( my vector(
3,138
python classes in detail (vproperties allow you to add behavior to data attributesclass my vector(object)def __init__(selfxy)self _x self _y def get_x(self)return self _x def set_x(selfx)self _x property(get_xset_xdefine getter using decorator syntax @property def (self)return self _y my vector( use the getter use the setter use the getter
3,139
python example (iimport random class die(object)derive from object for new style classes """simulate generic die ""def __init__(selfsides= )"""initialize and roll the die sides -number of faceswith values starting at one (default is ""self _sides sides leading underscore signals private self _value none value from last roll self roll(def roll(self)"""roll the die and return the result ""self _value random randrange(self _sidesreturn self _value
3,140
python example (iidef __str__(self)"""return string with nice description of the die state ""return "die with % sidescurrent value is % (self _sidesself _valueclass winnerdie(die)"""special die class that is more likely to return ""def roll(self)"""roll the die and return the result ""super(winnerdieselfroll(use super instead of die roll(selfif self _value = return self _value elsereturn super(winnerdieselfroll(
3,141
python example (iiidie die(die _sides we should not access thisbut nobody will stop us die roll for in range( )print die roll( print die this calls __str__ die with sidescurrent value is winner_die dice winnerdie(for in range( )print winner_die roll()
3,142
not bad
3,143
what is design patterndesign patterns are concrete solutions for reoccurring problems they satisfy the design principles and can be used to understand and illustrate them they provide name to communicate effectively with other programmers iterator pattern decorator pattern strategy pattern adapter pattern the essence of the iterator factory method pattern is to "provide way to access the elements of an aggregate object sequentially without exposing its underlying representation the decorator pattern is design pattern that allows behavior to be added to an existing object dynamically the strategy pattern (also known as the policy patternis particular software design patternwhereby algorithms behavior can be selected at runtime the adapter pattern is design pattern that translates one interface for class into compatible interface
3,144
3,145
problem how would you iterate elements from collectionmy_collection [' '' '' 'for in range(len(my_collection))print my_collection[ ]abc but what if my_collection does not support indexingmy_collection {' ' ' ' ' ' for in range(len(my_collection))print my_collection[ ]what will happen here this violates one of the design principles
3,146
description store the elements in collection (iterablemanage the iteration over the elements by means of an iterator object which keeps track of the elements which were already delivered iterator has next(method that returns an item from the collection when all items have been returned it raises stop iteration exception iterable provides an __iter__(methodwhich returns an iterator object
3,147
example (iclass myiterable(object)"""example iterable that wraps sequence ""def __init__(selfitems)"""store the provided sequence of items ""self items items def __iter__(self)return myiterator(selfclass myiterator(object)"""example iterator that is used by myiterable ""def __init__(selfmy_iterable)"""initialize the iterator my_iterable -instance of myiterable ""self _my_iterable my_iterable self _position
3,148
example (iidef next(self)if self _position len(self _my_iterable items)value self _my_iterable items[self _positionself _position + return value elseraise stopiteration(in python iterators also support iter by returning self def __iter__(self)return self
3,149
example (iiifirstlets perform the iteration manuallyiterable myiterable([ , , ]iterator iter(iterableor use iterable __iter__(trywhile trueitem iterator next(print item except stopiterationpass print "iteration done more elegant solution is to use the python for-loopfor item in iterableprint item print "iteration done in fact python lists are already iterablesfor item in [ , , ]print item
3,150
3,151
problem (iclass beverage(object)imagine some attributes like temperatureamount leftdef get_description(self)return "beveragedef get_cost(self)return class coffee(beverage)def get_description(self)return "normal coffeedef get_cost(self)return class tee(beverage)def get_description(self)return "teedef get_cost(self)return
3,152
problem (iiclass coffeewithmilk(coffee)def get_description(self)return super(coffeewithmilkselfget_description("with milkdef get_cost(self)return super(coffeewithmilkselfget_cost( class coffeewithmilkandsugar(coffeewithmilk)and so onwhat mess
3,153
description we have the following requirementsadding new ingredients like soy milk should be easy and work with all beveragesanybody should be able to add new custom ingredients without touching the original code (open-closed principle)there should be no limit to the number of ingredients use the decorator pattern here dude
3,154
solution class beverage(object)def get_description(self)return "beveragedef get_cost(self)return class coffee(beverage)#class beveragedecorator(beverage)def __init__(selfbeverage)super(beveragedecoratorself__init__(not really needed here self beverage beverage class milk(beveragedecorator)def get_description(self)#def get_cost(self)#coffee_with_milk milk(coffee()
3,155
3,156
problem class duck(object)def __init__(self)for simplicity this example class is stateless def quack(self)print "quack!def display(self)print "boring looking duck def take_off(self)print " ' running fastflapping with my wings def fly_to(selfdestination)print "now flying to % destination def land(self)print "slowing downextending legstouch down
3,157
problem (iclass redheadduck(duck)def display(self)print "duck with read head class rubberduck(duck)def quack(self)print "squeak!def display(self)print "small yellow rubber duck oh manthe rubberduck is able to flylooks like we have to override all the flying related methods but if we want to introduce decoyduck as well we will have to override all three methods again in the same way (dryand what if normal duck suffers broken wingideacreate flyingbehavior class which can be plugged into theduck class
3,158
solution (iclass flyingbehavior(object)"""default flying behavior ""def take_off(self)print " ' running fastflapping with my wings def fly_to(selfdestination)print "now flying to % destination def land(self)print "slowing downextending legstouch down class duck(object)def __init__(self)self flying_behavior flyingbehavior(def quack(self)print "quack!def display(self)print "boring looking duck def take_off(self)self flying_behavior take_off(def fly_to(selfdestination)self flying_behavior fly_to(destinationdef land(self)self flying_behavior land(
3,159
solution (iiclass nonflyingbehavior(flyingbehavior)"""flyingbehavior for ducks that are unable to fly ""def take_off(self)print "it' not working :-(def fly_to(selfdestination)raise exception(" ' not flying anywhere "def land(self)print "that won' be necessary class rubberduck(duck)def __init__(self)self flying_behavior nonflyingbehavior(def quack(self)print "squeak!def display(self)print "small yellow rubber duck class decoyduck(duck)def __init__(self)self flying_behavior nonflyingbehavior(def quack(self)print "def display(self)print "looks almost like real duck
3,160
3,161
problem lets say we obtained the following class from our collaboratorclass turkey(object)def fly_to(self)print " believe can fly def gobble(selfn)print "gobble how to integrate it with our duck simulatorturkeys can fly and gobble but they can not quack
3,162
description
3,163
solution class turkeyadapter(object)def __init__(selfturkey)self turkey turkey self fly_to turkey fly_to #delegate to native turkey method self gobble_count def quack(self)#adapt gobble to quack self turkey gobble(self gobble_countturkey turkey(turkeyduck turkeyadapter(turkeyturkeyduck fly_to( believe can fly turkeyduck quack(gobble gobble gobble adapter pattern applies several good design principlesuses composition to wrap the adaptee (turkeywith an altered interfacebinds the client to an interface not to an implementation
3,164
3,165
object models since python there co-exist two slightly dierent object models in the language old-style (classicclasses this is the model existing prior to python new-style classes :this is the preferred model for new code old style class apass class bpass ab () (type( =type(btrue type( new style class (object)pass class (object)pass ab () (type( =type(bfalse type(
3,166
new-style classes defined in the type and class unification effort in python (introduced without breaking backwards compatibilitysimplermore regular and more powerful it will be the default (and uniquein the future documents built-in types ( dictcan be subclassed propertiesattributes managed by get/set methods static and class methods (via descriptor apicooperative classes (sane multiple inheritancemeta-class programming unifying types and classes in python pep- making types look more like classes pep- subtyping built-in types
3,167
the class statement class classname(base-classes)statement(sclassname is variable that gets (re)bound to the class object after the class statement finishes executing base-classes is comma separated series of expressions whose values must be classes if it does not existsthe created class is old-style if all base-classes are old-stylethe created class is old-style otherwise it is new-style class since every type subclasses built-in objectwe can use object to mark class as new-style when no true bases exist the statements ( the class bodydene the set of class attributes which will be shared by all instances of the class
3,168
class-private attributes when statement in the body (or in method in the bodyuses an identifier starting with two underscores (but not ending with themsuch as __privatethe python compiler changes it to _classname__private this lets classes to use private names reducing the risk of accidentally duplicating names used elsewhere by convention all identifiers starting with single underscore are meant to be private in the scope that binds them class (object)private print __private attributeerrorclass has no attribute privateprint private
3,169
classes can be viewed as factories or templates for generadng new object instances each object instance takes on the properdes of the class from which it was created
3,170
3,171
defining class in python is done using the class keywordfollowed indented block defining class by in an python is done using with the cthe lass class contents keywordfollowed by an indented block with the class contents general format class data attributes class data value datam valuem def (self,arg ,argk)def (self,arg ,argk)class member functions
3,172
lassdefinition blockblock can cinclude multiple class definidon an include muldple functi funcdons ese represent the functionality or behaviors tha these represent the funcdonality or behaviors sociated with the class that are associated with the class class mathsdef subtract(self, , )return - def add(self, , )return + argument (selfrefers to the object itself ss functions differ from standard python functions
3,173
using class funcdons from outside class ss functions from outside class funcdons aby re rusing eferenced using the dot syntaxare referenced the bdot syntax(me( maths( subtract( , add( , no need to specify value for selfpython does this automatically ass functions from inside class erring to functions
3,174
no need to to mmaths(no need maths(specify value for for specify value subtract( , subtract( , self,selfpython doesdoes python this this automatically automatically add( , add( , using class funcdons from inside class calling funcdons in classes when referring to funcdons from within classwe must always prefix the funcdon name with self unctions from inside class functions from inside class ( self subtract()to functions ring to functions classa classs prefix thethe ways prefix withwith self me self ract()subtract(class mathsclass mathsdef def subtract(self, , )subtract(self, , )return - - return def def testsub(self)testsub(self)print self subtract( , print self subtract( , tell tell python to use function python to use function associated withwith this this object associated object
3,175
class attribute class attribute defined at top of class persondefined at top of class personclass company "ucdcompany "ucdclass person( person( person( person( age age print age print age person(person( person( company person()"ibmprint company company "ibm'ibmprint company 'ibmdef def __init__(self)__init__(self)self age self age = instance attribute instance attribute defined inside class defined inside class function function the self prefix the self prefix is is always required always required change attribute ageage changetotoinstance instance attribute affects only the associated affects only the associated instance ( instance ( change to class attribute company affects ( and company changealltoinstances class attribute affects all instances ( and
3,176
when an instance of class is createdthe class constructor function is automatically called when an instance of class is createdthe class constructor constructor is always named __init__(the funcdon is automadcally called it contains code for initializing new instance of the class to the cinitial onstructor always setting named _instance _init__(attribute valuesspecific stateis ( contains code isfor inidalizing new instance of is the class to presentana empty object created if *noit constructor specific inidal state ( setng instance akribute valuesclass persondef __init__selfs )self name def helloself )print "hello"self name person("john" hello(hello john constructor function taking initial value for instance attribute name calls __init__(on person
3,177
class inheritance is designed to model reladonships of the type " is ( " triangle is shape"
3,178
the funcdons and akributes of superclass are inherited by subclass an inherited class can overridemodify or augment the funcdons and akributes of its parent class
3,179
3,180
class shapedef __init__self )self color ( , , simple subclass inheriting from shape class rectangle(shape)need to call def __init__selfwh )constructor shape __init__self function in self width superclass self height def areaself )return self width*self height rectangle print width print height print area( print color ( construct object instance inherited attribute
3,181
when inheridng from classwe can alter the behavior of the original superclass by "overridingfuncdons ( declaring funcdons in the subclass with the same namefuncdons in subclass take precedence over funcdons in superclass
3,182
( declaring functions in the subclass with the same nameoverriding notefunctions in subclass take precedence over functions in superclass class counterdef __init__(self)self value def increment(self)self value + cc customcounter( cc increment(cc print_current(current value is class customcounter(counter)def __init__(self,size)counter __init__(selfself stepsize size overriding def increment(self)self value +self stepsize calls increment(on customcounter not counter
3,183
classes can built from other smaller classes,allowing can bebe built from other smaller classesallowing us to classes model of the type "has ( us to relationships model reladonships of " he has type " ( department studentsdepartment has shas tudentsclass departmentdef __init__self )self students [class studentdef __init__self,last,first )self lastname last self firstname first def enrollselfstudent )self students append(studentcompsci department(compsci enrollstudent"smith""johncompsci enrollstudent"murphy""alicefor in compsci studentsprint "% % ( firstname, lastnamejohn smith create student instances and add to department instance
3,184
class is special data type which defines how to build certain kind of object the class also stores some data items that are shared by all the instances of this class instances are objects that are created which follow the definition given inside of the class python doesn' use separate class interface definitions as in some languages you just define the class and then use it
3,185
define method in class by including function definitions within the scope of the class block there must be special first argument self in all of method definitions which gets bound to the calling instance there is usually special method called __init__ in most classes we'll talk about both later
3,186
class student""" class representing student ""def __init__(self, , )self full_name self age def get_age(self)return self age
3,187
instances
3,188
there is no "newkeyword as in java just use the class name with notation and assign the result to variable __init__ serves as constructor for the class usually does some initialization work the arguments passed to the class name are given to its __init__(method sothe __init__ method for student is passed "boband and the new class instance is bound to bb student("bob"
3,189
an __init__ method can take any number of arguments like other functions or methodsthe arguments can be defined with default valuesmaking them optional to the caller howeverthe first argument self in the definition of __init__ is special
3,190
the first argument of every method is reference to the current instance of the class by conventionwe name this argument self in __init__self refers to the object currently being createdsoin other class methodsit refers to the instance whose method was called similar to the keyword this in java or +but python uses self more often than java uses this
3,191
although you must specify self explicitly when defining the methodyou don' include it when calling the method python passes it for you automatically defining methodcalling method(this code inside class definition def set_age(selfnum)self age num set_age(
3,192
when you are done with an objectyou don' have to delete or free it explicitly python has automatic garbage collection python will automatically detect when all of the references to piece of memory have gone out of scope automatically frees that memory generally works wellfew memory leaks there' also no "destructormethod for classes
3,193
and methods
3,194
class student""" class representing student ""def __init__(self, , )self full_name self age def get_age(self)return self age
3,195
student("bob smith" full_name access attribute "bob smithf get_age(access method
3,196
problemoccasionally the name of an attribute or method of class is only given at run time solutiongetattr(object_instancestringstring is string which contains the name of an attribute or method of class getattr(object_instancestringreturns reference to that attribute or method
3,197
student("bob smith" getattr( "full_name""bob smithgetattr( "get_age"<method get_age of class studentclass at getattr( "get_age")(call it getattr( "get_birthday"raises attributeerror no method
3,198
student("bob smith" hasattr( "full_name"true hasattr( "get_age"true hasattr( "get_birthday"false
3,199
the non-method data stored by objects are called attributes data attributes variable owned by particular instance of class each instance has its own value for it these are the most common kind of attribute class attributes owned by the class as whole all class instances share the same value for it called "staticvariables in some languages good for ( class-wide constants and ( building counter of how many instances of the class have been made