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 ...
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(...
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 subc...
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('e...
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 +-attributeerr...
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...
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 ha...
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 ...
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""onc...
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 t...
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...
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...
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 skillorac...
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...
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...
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 c...
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 lev...
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...
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 t...
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 bui...
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...
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...
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 modu...
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 ju...
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 betwe...
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 th...
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 simpl...
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 a...
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...
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 ...
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...
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 ...
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 o...
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 desig...
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 exceptio...
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 it...
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 ...
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)retur...
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...
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 ...
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 dow...
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 ...
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 flyingbehavi...
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...
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 turkeyduc...
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 clas...
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 a...
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-classe...
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 el...
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...
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 +...
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 func...
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 ...
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 setti...
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 (...
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__(se...
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 __ini...
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 ...
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 th...
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 ...
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 "destructormetho...
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 "staticvariabl...