id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
3,200 | data attributes are created and initialized by an __init__(method simply assigning to name creates the attribute inside the classrefer to data attributes using self --for exampleself full_name class teacher" class representing teachers def __init__(self, )self full_name def print_name(self)print self full_name |
3,201 | because all instances of class share one copy of class attributewhen any instance changes itthe value is changed for all instances class attributes are defined within class definition and outside of any method since there is one of these attributes per class and not one per instancethey're accessed via different notati... |
3,202 | class counteroverall_total class attribute def __init__(self)self my_total data attribute def increment(self)counter overall_total counter overall_total self my_total self my_total counter( counter( increment( increment( increment( my_total __class__ overall_total my_total __class__ overall_total |
3,203 | classes can extend the definition of other classes allows use (or extensionof methods and attributes already defined in the previous one to define subclassput the name of the superclass in parens after the subclass' name on the first line of the definition class cs_student(student)python has no 'extendskeyword like jav... |
3,204 | python has two kinds of classesold and new (more on this laterold style classes use depth-firstleft-to-right access new classes use more complexdynamic approach class ao() class bo(ao) class co(ao) class do(bo,co)pass ao ao(bo bo(co co(do do(from mi import ao bo co do |
3,205 | to redefine method of the parent classinclude new definition using the same name in the subclass the old code won' get executed to execute the method in the parent class in addition to new code for some methodexplicitly call the parent' version of method parentclass methodname(self, , ,cthe only time you ever explicitl... |
3,206 | class student" class representing student def __init__(self, , )self full_name self age def get_age(self)return self age class cs_student (student)" class extending student def __init__(self, , , )student __init__(self, , #call __init__ for student self section_num def get_age()#redefines get_age method entirely print ... |
3,207 | same as redefining any other method commonlythe ancestor' __init__ method is executed in addition to new commands you'll often see something like this in the __init__ method of subclassesparentclass __init__(selfxywhere parentclass is the name of the parent' class |
3,208 | methods and attributes |
3,209 | classes contain many methods and attributes that are always included most define automatic functionality triggered by special operators or usage of that class built-in attributes define information that must be stored for all classes all built-in members have double underscores around their names__init__ __doc__ |
3,210 | the method __repr__ exists for all classesand you can always redefine it __repr__ specifies how to turn an instance of the class into string *print sometimes calls __repr__(to produce string for object typing at the repl prompt calls __repr__ to determine what to display as output |
3,211 | class studentdef __repr__(self)return " ' named self full_name student("bob smith" print ' named bob smith " ' named bob smith |
3,212 | you can redefine these as well__init__ the constructor for the class __cmp__ define how =works for class __len__ define how lenobj works __copy__ define how to copy class other built-in methods allow you to give class the ability to use notation like an array or notation like function call |
3,213 | these attributes exist for all classes __doc__ variable for documentation string for class __class__ variable which gives you reference to the class from any instance of it __module__ variable which gives reference to the module in which the particular class is defined __dict__ :the dictionary that is actually the name... |
3,214 | amahdy abdelaziz has more than years of experience in software engineering using several languages and frameworks over the last yearshe has focused on android and mobile developmentincluding cross-platform toolsand android internalssuch as building custom roms and customizing aosp for embedded devices he is currently t... |
3,215 | com/) fintech start-up helping small and medium businesses raise capital from investors and different financial institutions in the pasthe has worked with early stage start-ups such as blockbeacon (santa monicaand pricepoint (caand large organizations such as national instrumentsbangaloreand googlenew york krishna got ... |
3,216 | of professional experience in operations and development and more than years of software development experience he is passionate about new technologies and loves to take creative approaches to solve complex problems in his spare timehe learns new languages and new platformsplays video gamesand spends time with his fami... |
3,217 | support filesebooksdiscount offersand more for support files and downloads related to your bookplease visit www packtpub com did you know that packt offers ebook versions of every book publishedwith pdf and epub files availableyou can upgrade to the ebook version at www packtpub com and as print book customeryou are en... |
3,218 | the second edition have confession to make when wrote the first edition of this booki didn' have clue what was doing thought knew python and thought knew how to write quickly learned that this was false luckilyi became adept at both by finishing the booki was so afraid that people wouldn' like python object oriented pr... |
3,219 | the next onebut there were few key places where the topic change was jarringor worseirrelevant the two preceding the discussions about design patterns have been reorganizedreversedand split into three that flow cleanly into the next topic 've also removed an entire on third-party libraries for python this made more sen... |
3,220 | preface object-oriented design vii objects in python introducing object-oriented objects and classes specifying attributes and behaviors data describes objects behaviors are actions hiding details and creating the public interface composition inheritance inheritance provides abstraction multiple inheritance case study ... |
3,221 | who can access my datathird-party libraries case study exercises summary when objects are alike expecting the unexpected basic inheritance extending built-ins overriding and super multiple inheritance the diamond problem different sets of arguments polymorphism abstract base classes using an abstract base class creatin... |
3,222 | case study exercises summary python data structures empty objects tuples and named tuples named tuples dictionaries dictionary use cases using defaultdict counter lists sorting lists sets extending built-ins queues fifo queues lifo queues priority queues case study exercises summary python object-oriented shortcuts pyt... |
3,223 | strings and serialization strings string manipulation string formatting escaping braces keyword arguments container lookups object lookups making it look right strings are unicode mutable byte strings regular expressions matching patterns converting bytes to text converting text to bytes matching selection of character... |
3,224 | case study exercises summary python design patterns python design patterns ii testing object-oriented programs the decorator pattern decorator example decorators in python the observer pattern an observer example the strategy pattern strategy example strategy in python the state pattern state example state versus strat... |
3,225 | testing with py test one way to do setup and cleanup completely different way to set up variables skipping tests with py test imitating expensive objects how much testing is enoughcase study implementing it exercises summary concurrency shared memory the global interpreter lock threads the many problems with threads th... |
3,226 | this book introduces the terminology of the object-oriented paradigm it focuses on object-oriented design with step-by-step examples it guides us from simple inheritanceone of the most useful tools in the object-oriented programmer' toolbox through exception handling to design patternsan object-oriented way of looking ... |
3,227 | objects in pythondiscusses classes and objects and how they are used in python we will learn about attributes and behaviors on python objectsand also the organization of classes into packages and modules lastlywe will see how to protect our data when objects are alikegives us more in-depth look into inheritance it cove... |
3,228 | testing object-oriented programsopens with why testing is so important in python applications it emphasizes test-driven development and introduces two different testing suitesunittest and py test finallyit discusses mocking test objects and code coverage concurrencyis whirlwind tour of python' support (and lack thereof... |
3,229 | who this book is for this book specifically targets people who are new to object-oriented programming it assumes you have basic python skills you'll learn object-oriented principles in depth it is particularly useful for system administrator types who have used python as "gluelanguage and would like to improve their pr... |
3,230 | any command-line input or output is written as followsc contact("john ""johna@example net" contact("john ""johnb@example net" contact("jenna ""jennac@example net"[ name for in contact all_contacts search('john')['john ''john 'new terms and important words are shown in bold words that you see on the screenin menus or di... |
3,231 | downloading the example code you can download the example code files from your account at packtpub com for all the packt publishing books you have purchased if you purchased this book elsewhereyou can visit and register to have the files -mailed directly to you errata although we have taken every care to ensure the acc... |
3,232 | in software developmentdesign is often considered as the step done before programming this isn' truein realityanalysisprogrammingand design tend to overlapcombineand interweave in this we will cover the following topicswhat object-oriented means the difference between object-oriented design and object-oriented programm... |
3,233 | if you've read any hypeyou've probably come across the terms object-oriented analysisobject-oriented designobject-oriented analysis and designand objectoriented programming these are all highly related concepts under the general object-oriented umbrella in factanalysisdesignand programming are all stages of software de... |
3,234 | yeahrightit would be lovely if the world met this ideal and we could follow these stages one by onein perfect orderlike all the old textbooks told us to as usualthe real world is much murkier no matter how hard we try to separate these stageswe'll always find things that need further analysis while we're designing when... |
3,235 | this diagram shows that an orange is somehow associated with basket and that an apple is also somehow associated with barrel association is the most basic way for two classes to be related uml is very popular among managersand occasionally disparaged by programmers the syntax of uml diagram is generally pretty obviousy... |
3,236 | the beauty of uml is that most things are optional we only need to specify as much information in diagram as makes sense for the current situation in quick whiteboard sessionwe might just quickly draw lines between boxes in formal documentwe might go into more detail in the case of apples and barrelswe can be fairly co... |
3,237 | data describes objects let' start with data data typically represents the individual characteristics of certain object class can define specific sets of characteristics that are shared by all objects of that class any specific object can have different data values for the given characteristics for exampleour three oran... |
3,238 | orange basket +weightfloat +locationstring +orchardstring +orangeslist +date_pickeddate +basketbasket go in go in apple barrel +colorstring +weightfloat +barrelbarrel +sizeint +appleslist depending on how detailed our design needs to bewe can also specify the type for each attribute attribute types are often primitives... |
3,239 | parameters to method are list of objects that need to be passed into the method that is being called (the objects that are passed in from the calling object are usually referred to as argumentsthese objects are used by the method to perform whatever behavior or task it is meant to do returned values are the results of ... |
3,240 | hiding details and creating the public interface the key purpose of modeling an object in object-oriented design is to determine what the public interface of that object will be the interface is the collection of attributes and methods that other objects can use to interact with that object they do not needand are ofte... |
3,241 | rememberprogram objects may represent real objectsbut that does not make them real objects they are models one of the greatest gifts of modeling is the ability to ignore irrelevant details the model car built as child may look like real thunderbird on the outsidebut it doesn' run and the driveshaft doesn' turn these de... |
3,242 | don' try to model objects or actions that might be useful in the future model exactly those tasks that the system needs to performand the design will naturally gravitate towards the one that has an appropriate level of abstraction this is not to say we should not think about possible future design modifications our des... |
3,243 | the objects in an object-oriented system occasionally represent physical objects such as peoplebooksor telephones more oftenhoweverthey represent abstract ideas people have namesbooks have titlesand telephones are used to make calls callstitlesaccountsnamesappointmentsand payments are not usually considered objects in ... |
3,244 | what is thisit doesn' quite look like our earlier class diagrams that' because it isn' class diagramthis is an object diagramalso called an instance diagram it describes the system at specific state in timeand is describing specific instances of objectsnot the interaction between classes rememberboth players are member... |
3,245 | let' describe our current chess set composition and add some attributes to the objects to hold the composite relationshipsposition player +chess_boardboard make move chess set +pieceslist +boardboard piece board +chess_setchessset +chess_setchessset +positionsposition the composition relationship is represented in uml ... |
3,246 | for examplethere are chess pieces in our chess setbut there are only six different types of pieces (pawnsrooksbishopsknightskingand queen)each of which behaves differently when it is moved all of these classes of piece have propertiessuch as color and the chess set they are part ofbut they also have unique shapes when ... |
3,247 | overriding methods in subtypes allows very powerful object-oriented systems to be developed for exampleif we wanted to implement player class with artificial intelligencewe might provide calculate_move method that takes board object and decides which piece to move where very basic class might randomly choose piece and ... |
3,248 | this sort of polymorphism in python is typically referred to as duck typing"if it walks like duck or swims like duckit' duckwe don' care if it really is duck (inheritance)only that it swims or walks geese and swans might easily be able to provide the duck-like behavior we are looking for this allows future designers to... |
3,249 | inheritance is very powerful tool for extending behavior it is also one of the most marketable advancements of object-oriented design over earlier paradigms thereforeit is often the first tool that object-oriented programmers reach for howeverit is important to recognize that owning hammer does not turn screws into nai... |
3,250 | the relationship between author and book is clearly associationsince you would never say" book is an author(it' not inheritance)and saying " book has an author"though grammatically correctdoes not imply that authors are part of books (it' not aggregationindeedany one author may be associated with multiple books we shou... |
3,251 | likelythese iterations would all occur in an initial meeting with the librarian before this meetinghoweverwe can already sketch out most basic design for the objects we have concretely identifiedcatalog +search(author book +name +isbn +authors +title +subject +dds number armed with this basic diagram and pencil to inte... |
3,252 | the librarian understands the gist of our sketched diagrambut is bit confused by the locate functionality we explain using specific use case where the user is searching for the word "bunniesthe user first sends search request to the catalog the catalog queries its internal list of items and finds book and dvd with "bun... |
3,253 | the half arrowheads indicate asynchronous messages sent to or from an object an asynchronous message typically means the first object calls method on the second objectwhich returns immediately after some processingthe second object calls method on the first object to give it value this is in contrast to normal method c... |
3,254 | the multiplicity of the contributor/libraryitem relationship is many-to-manyas indicated by the character at both ends of one relationship any one library item might have more than one contributor (for exampleseveral actors and director on dvdand many authors write many booksso they would be attached to multiple librar... |
3,255 | just looking at this class diagramit feels like we are doing something wrong it is bulky and fragile it may do everything we needbut it feels like it will be hard to maintain or extend there are too many relationshipsand too many classes would be affected by modifications to any one class it looks like spaghetti and me... |
3,256 | at firstthis composition relationship looks less natural than the inheritance-based relationships howeverit has the advantage of allowing us to add new types of contributions without adding new class to the design inheritance is most useful when the subclasses have some kind of specialization specialization is creating... |
3,257 | firstthink about recent programming project you've completed identify the most prominent object in the design try to think of as many attributes for this object as possible did it havecolorweightsizeprofitcostnameid numberpricestylethink about the attribute types were they primitives or classeswere some of those attrib... |
3,258 | sowe now have design in hand and are ready to turn that design into working programof courseit doesn' usually happen this way we'll be seeing examples and hints for good software design throughout the bookbut our focus is object-oriented programming solet' have look at the python syntax that allows us to create object-... |
3,259 | the class name must follow standard python variable naming rules (it must start with letter or underscoreand can only be comprised of lettersunderscoresor numbersin additionthe python style guide (search the web for "pep "recommends that classes should be named using camelcase notation (start with capital letterany sub... |
3,260 | downloading the example code you can download the example code files for all packt books you have purchased from your account at if you purchased this book elsewhereyou can visit packtpub com/support and register to have the files -mailed directly to you adding attributes nowwe have basic classbut it' fairly useless it... |
3,261 | making it do something nowhaving objects with attributes is greatbut object-oriented programming is really about the interaction between objects we're interested in invoking actions that cause things to happen to those attributes it is time to add behaviors to our classes let' model couple of actions on our point class... |
3,262 | notice that when we call the reset(methodwe do not have to pass the self argument into it python automatically takes care of this for us it knows we're calling method on the objectso it automatically passes that object to the method howeverthe method really is just function that happens to be on class instead of callin... |
3,263 | def move(selfxy)self self def reset(self)self move( def calculate_distance(selfother_point)return math sqrt(self other_point )** (self other_point )** how to use itpoint point(point point(point reset(point move( , print(point calculate_distance(point )assert (point calculate_distance(point =point calculate_distance(poi... |
3,264 | the sample code at the end of the preceding example shows how to call method with argumentssimply include the arguments inside the parenthesesand use the same dot notation to access the method just picked some random positions to test the methods the test code calls each method and prints the results on the console the... |
3,265 | we can catch and recover from this errorbut in this caseit feels like we should have specified some sort of default value perhaps every new object should be reset(by defaultor maybe it would be nice if we could force the user to tell us what those positions should be when they create the object most object-oriented pro... |
3,266 | what if we don' want to make those two arguments requiredwellthen we can use the same syntax python functions use to provide default arguments the keyword argument syntax appends an equals sign after each variable name if the calling object does not provide this argumentthen the default argument is used instead the var... |
3,267 | docstring should clearly and concisely summarize the purpose of the class or method it is describing it should explain any parameters whose usage is not immediately obviousand is also good place to include short examples of how to use the api any caveats or problems an unsuspecting user of the api should be aware of sh... |
3,268 | try typing or loading (rememberit' python - filename pythis file into the interactive interpreter thenenter help(pointat the python prompt you should see nicely formatted documentation for the classas shown in the following screenshotmodules and packages nowwe know how to create classes and instantiate objectsbut how d... |
3,269 | the import statement is used for importing modules or specific classes or functions from modules we've already seen an example of this in our point class in the previous section we used the import statement to get python' built-in math module and use its sqrt function in our distance calculation here' concrete example ... |
3,270 | some sources say that we can import all classes and functions from the database module using this syntaxfrom database import don' do this every experienced python programmer will tell you that you should never use this syntax they'll use obscure justifications such as "it clutters up the namespace"which doesn' make muc... |
3,271 | organizing the modules as project grows into collection of more and more moduleswe may find that we want to add another level of abstractionsome kind of nested hierarchy on our moduleslevels howeverwe can' put modules inside modulesone file can hold only one file after alland modules are nothing more than python files ... |
3,272 | or from ecommerce import products product products product(the import statements use the period operator to separate packages or modules these statements will work from any module we could instantiate product class using this syntax in main pyin the database moduleor in either of the two payment modules indeedassuming ... |
3,273 | we can use more periods to go further up the hierarchy of coursewe can also go down one side and back up the other we don' have deep enough example hierarchy to illustrate this properlybut the following would be valid import if we had an ecommerce contact package containing an email module and wanted to import the send... |
3,274 | organizing module contents inside any one modulewe can specify variablesclassesor functions they can be handy way to store the global state without namespace conflicts for examplewe have been importing the database class into various modules and then instantiating itbut it might make more sense to have only one databas... |
3,275 | as these two examples illustrateall module-level code is executed immediately at the time it is imported howeverif it is inside method or functionthe function will be createdbut its internal code will not be executed until the function is called this can be tricky thing for scripts (such as the main script in our -comm... |
3,276 | actuallyno this is the typical order of things in python programbut it' not the only possible layout classes can be defined anywhere they are typically defined at the module levelbut they can also be defined inside function or methodlike thisdef format_string(stringformatter=none)'''format string using the formatter ob... |
3,277 | who can access my datamost object-oriented programming languages have concept of access control this is related to abstraction some attributes and methods on an object are marked privatemeaning only that object can access them others are marked protectedmeaning only that class and any subclasses have access the rest ar... |
3,278 | if we load this class and test it in the interactive interpreterwe can see that it hides the plain text string from the outside worldsecret_string secretstring("acmetop secret""antwerp"print(secret_string decrypt("antwerp")acmetop secret print(secret_string __plain_texttraceback (most recent call last)file ""line in at... |
3,279 | third-party libraries python ships with lovely standard librarywhich is collection of packages and modules that are available on every machine that runs python howeveryou'll soon find that it doesn' contain everything you need when this happensyou have two optionswrite supporting package yourself use somebody else' cod... |
3,280 | insteadpython supplies the venv tool this utility basically gives you mini python installation called virtual environment in your working directory when you activate the mini pythoncommands related to python will work on that directory instead of the system directory so when you run pip or pythonit won' touch the syste... |
3,281 | the obvious object is the note objectless obvious one is notebook container object tags and dates also seem to be objectsbut we can use dates from python' standard library and comma-separated string for tags to avoid complexityin the prototypelet' not define separate classes for these objects note objects have attribut... |
3,282 | commandoption menu notebook +noteslist +search(filter:str)list +new_note(memo,tags="+modify_memo(note_id,memo+modify_tags(note_id,tags note +memo +creation_date +tags +match(search_filter:str)boolean before writing any codelet' define the folder structure for this project the menu interface should clearly be in its own... |
3,283 | string in searches and store tags for each note ''def __init__(selfmemotags='')'''initialize note with memo and optional space-separated tags automatically set the note' creation date and unique id ''self memo memo self tags tags self creation_date datetime date today(global last_id last_id + self id last_id def match(... |
3,284 | it looks like everything is behaving as expected let' create our notebook nextclass notebook'''represent collection of notes that can be taggedmodifiedand searched ''def __init__(self)'''initialize notebook with an empty list ''self notes [def new_note(selfmemotags='')'''create new note and add it to the list ''self no... |
3,285 | notes[ id notes[ id notes[ memo 'hello worldn search("hello"[<notebook note object at xb ac> search("world"[ modify_memo( "hi world" notes[ memo 'hi worldit does work the code is little messy thoughour modify_tags and modify_memo methods are almost identical that' not good coding practice let' see how we can improve it... |
3,286 | from notebook import notebooknote class menu'''display menu and respond to choices when run ''def __init__(self)self notebook notebook(self choices " "self show_notes" "self search_notes" "self add_note" "self modify_note" "self quit def display_menu(self)print(""notebook menu show all notes search notes add note modif... |
3,287 | filter input("search for"notes self notebook search(filterself show_notes(notesdef add_note(self)memo input("enter memo"self notebook new_note(memoprint("your note has been added "def modify_note(self)id input("enter note id"memo input("enter memo"tags input("enter tags"if memoself notebook modify_memo(idmemoif tagssel... |
3,288 | if we test this codewe'll find that modifying notes doesn' work there are two bugsnamelythe notebook crashes when we enter note id that does not exist we should never trust our users to enter correct dataeven if we enter correct idit will crash because the note ids are integersbut our menu is passing string the latter ... |
3,289 | exercises write some object-oriented code the goal is to use the principles and syntax you learned in this to ensure you can use itinstead of just reading about it if you've been working on python projectgo back over it and see if there are some objects you can create and add properties or methods to if it' largetry di... |
3,290 | in the programming worldduplicate code is considered evil we should not have multiple copies of the sameor similarcode in different places there are many ways to merge pieces of code or objects that have similar functionality in this we'll be covering the most famous object-oriented principleinheritance as discussed in... |
3,291 | this is inheritancethis example istechnicallyno different from our very first example in objects in pythonsince python automatically inherits from object if we don' explicitly provide different superclass superclassor parent classis class that is being inherited from subclass is class that is inheriting from superclass... |
3,292 | this is simple class that allows us to track couple pieces of data about each contact but what if some of our contacts are also suppliers that we need to order supplies fromwe could add an order method to the contact classbut that would allow people to accidentally order things from contacts who are customers or family... |
3,293 | extending built-ins one interesting use of this kind of inheritance is adding functionality to built-in classes in the contact class seen earlierwe are adding contacts to list of all contacts what if we also wanted to search that list by namewellwe could add method on the contact class to search itbut it feels like thi... |
3,294 | in realitythe [syntax is actually so-called syntax sugar that calls the list(constructor under the hood the list data type is class that we can extend in factthe list itself extends the object classisinstance([]objecttrue as second examplewe can extend the dict classwhich issimilar to the listthe class that is construc... |
3,295 | as we saw in objects in pythonwe can do this easily by just setting phone attribute on the contact after it is constructed but if we want to make this third variable available on initializationwe have to override __init__ overriding means altering or replacing method of the superclass with new method (with the same nam... |
3,296 | super(call can be made inside any methodnot just __init__ this means all methods can be modified via overriding and calls to super the call to super can also be made at any point in the methodwe don' have to make the call as the first line in the method for examplewe may need to manipulate or validate incoming paramete... |
3,297 | contact all_contacts [ send_mail("hellotest -mail here"sending mail to jsmith@example net the contact initializer is still adding the new contact to the all_contacts listand the mixin is able to send mail to self email so we know everything is working this wasn' so hardand you're probably wondering what the dire warnin... |
3,298 | another option would be to create new address class to hold those strings togetherand then pass an instance of this class into the __init__ method of our friend class the advantage of this solution is that we can add behavior (saya method to give directions or to print mapto the data instead of just storing it statical... |
3,299 | in this examplewe directly call the __init__ function on each of the superclasses and explicitly pass the self argument this example technically workswe can access the different variables directly on the class but there are few problems firstit is possible for superclass to go uninitialized if we neglect to explicitly ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.