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 notationaccess class attributes using self __class__ name notation -this is just one way to do this the safest in general class samplex def increment(self)self __class__ + sample( increment( __class__ |
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 java multiple inheritance is supported |
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 explicitly pass 'selfas an argument is when calling method of an ancestor |
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 "agestr(self age |
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 namespace for class (but not its superclassesusefuldir(xreturns list of all methods and attributes defined for object |
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 teaching python at information technology institution you can visit his websitegrigoriy beziuk is former cio of crowdage foundationacting as an independent software developer as this book was being written he has worked with wide variety of programming languages and technologiesincluding different versions of python in different environmentsranging from purely scientific ones to modern production-scale web development issues would like to thank my momlarisa beziukfor giving me the gift of lifeall of my teachers and friends for making my life more interestingand all of my beloved onesformer and present for welleverything |
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 introduced to python and foss during his college days and has continued to use it extensively in his personal projects and also professionally at work because of his liking for teaching and mentoringhe visits different universitiesconducting workshops whenever he gets an opportunity he holds master' degree in computer science from the university of southern californialos angelesand bachelor' degree in information science and engineering from the bms college of engineeringbangalore he can be reached through his -mailkrishna@krishnabharadwaj infoor his websitejustin cano is recent graduate from the university of californiariversidewith bs in computer engineering and is currently working as software engineer in the silicon valley area with hopes of moving to big tech company such as google or apple he first started programming in the sixth gradecreating smallprimitive websites in html and css he started to learn computer science theory and +in his first year at uc riverside and then started learning python in his third year justin admits that at firsthe wasn' immediately attracted to pythonsince abstractions between +and python are very different it wasn' until he began to express more of an interest in coding contests and challenges that he began to show interest in pythonmainly because he feels that the readability and elegance of the python syntax allows him to quickly and more naturally turn ideas and thought processes into python code he now writes python code regularlyoften to create mock-ups or prototypes of software applications before moving on to more domain-specific language would like to thank the author for taking the time to write this book as have received lot of valuable insights and information on the python language and design patterns this book has strengthened my understanding of pythonand believe that am now more knowledgeable python programmer |
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 family in the beautiful region of british columbiacanadawhere he now lives after emigrating from france in claudio rodriguez started working on plcs for gebut his main goal has always been research and development and turning dreams into reality this made him move from automation engineering to software engineering and the structured way of softwareoodthe remote team working from the comfort of his computer was just too powerful not to take advantage of during his master'she got to learn the proper place to look for resources and found friend in books and research papers and conferences eventuallyhe started working on system to control an electric arc furnacebut the needs of his clients moved him into taking further control of technology he has deep love for complex ai and can be seen surrounded by papersbooksand computer to test thingsbut he keeps things real by delivering beautiful and dynamic applications for his customers |
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 entitled to discount on the ebook copy get in touch with us at service@packtpub com for more details at www packtpub comyou can also read collection of free technical articlessign up for range of free newsletters and receive exclusive discounts and offers on packt books and ebooks tm do you need instant solutions to your it questionspacktlib is packt' online digital book library hereyou can searchaccessand read packt' entire library of books why subscribefully searchable across every book published by packt copy and pasteprintand bookmark content on demand and accessible via web browser free access for packt account holders if you have an account with packt at www packtpub comyou can use this to access packtlib today and view entirely free books simply use your login credentials for immediate access |
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 programming that skipped pycon for two years straight after couple dozen positive reviewsmy confidence was boosted and finally attended pycon in santa clara soon discovered that nobody had ever heard of me or my book so much for arrogancei was also afraid to reread the book after completing it so while it has received many accoladesthe copy on my shelf has remained firmly shutsave for when open it for reference to answer reader' query in preparing this second editioni was finally forced to face my demons to my surprise and joyi discovered that the book wrote five years ago was both accurate and enjoyablejust as many reviewers had suggested shortly after that initial rereadingi got my first ever negative review on amazon it would have been devastating had read it directly after completing the project fortunatelyfour years of good reviews and my own confidence in the writing allowed me to ignore the vitriol and take the remainder as constructive feedback the truth is many of the flaws the reviewer had pointed out were features at the time the book was originally published python object oriented programming was showing its ageand it was clearly time for an update you're holding the result in your hands (or flipping through it on your -readeri've often wondered why authors describe in detail what has changed between the editions of technical book meanseriouslyhow many people reading this second edition have read the first oneas with software versionsyou safely assume the latest edition is the bestand you don' really care about the project' history and yetthis project has consumed so much of my life over the past year that can' leave without few words about how much better the book has become |
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 sense when both the book and python were new there were only few libraries that had been ported to python and it was reasonable to have best of breed discussion about each of them howeveri was unable to cover any of those topics in detailand franklyi could write an entire book on any one of them finallyi've added an entire new on concurrency struggled with this and can freely admit that it' not directly related to object-oriented programming howevermuch like the on unit testingi think that understanding concurrency is an integral part of all programming and especially of object-oriented programming in the python ecosystem you areof coursefree to skip those if you disagree (or until you discover reason to change your mindenjoy the book and your journey into the world of object-oriented programming dusty phillips |
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 exercises summary creating python classes adding attributes making it do something talking to yourself more arguments initializing the object explaining yourself modules and packages organizing the modules organizing module contents absolute imports relative imports [ |
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 creating an abstract base class demystifying the magic case study exercises summary raising exceptions raising an exception the effects of an exception handling exceptions the exception hierarchy defining our own exceptions case study exercises summary when to use object-oriented programming treat objects as objects adding behavior to class data with properties properties in detail decorators another way to create properties deciding when to use properties manager objects removing duplicate code in practice ii |
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 python built-in functions the len(function reversed enumerate file / placing it in context an alternative to method overloading default arguments variable argument lists unpacking arguments functions are objects too using functions as attributes callable objects case study exercises summary iii |
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 characters escaping characters matching multiple characters grouping patterns together getting information from regular expressions making repeated regular expressions efficient serializing objects customizing pickles serializing web objects case study exercises summary the iterator pattern design patterns in brief iterators the iterator protocol comprehensions list comprehensions set and dictionary comprehensions generator expressions generators yield items from another iterable coroutines back to log parsing closing coroutines and throwing exceptions the relationship between coroutinesgeneratorsand functions iv |
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 strategy state transition as coroutines the singleton pattern singleton implementation the template pattern template example exercises summary the adapter pattern the facade pattern the flyweight pattern the command pattern the abstract factory pattern the composite pattern exercises summary why testtest-driven development unit testing assertion methods reducing boilerplate and cleaning up organizing and running tests ignoring broken tests [ |
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 thread overhead multiprocessing multiprocessing pools queues the problems with multiprocessing futures asyncio asyncio in action reading an asyncio future asyncio for networking using executors to wrap blocking code streams case study exercises summary executors index vi |
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 at object-oriented concepts along the waywe'll learn to integrate the object-oriented and not-so-object-oriented aspects of the python programming language we will learn the complexities of string and file manipulationemphasizing (as python doesthe difference between binary and textual data we'll then cover the joys of unit testingusing not onebut two unit testing frameworks finallywe'll explorethrough python' various concurrency paradigmshow to make objects work well together at the same time what this book covers this book is loosely divided into four major parts in the first four we will dive into the formal principles of object-oriented programming and how python leverages them in through we will cover some of python' idiosyncratic applications of these principles by learning how they are applied to variety of python' built-in functions through cover design patternsand the final two discuss two bonus topics related to python programming that may be of interest object-oriented designcovers important object-oriented concepts it deals mainly with terminology such as abstractionclassesencapsulationand inheritance we also briefly look at uml to model our classes and objects vii |
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 covers multiple inheritance and shows us how to extend built-ins this also covers how polymorphism and duck typing work in python expecting the unexpectedlooks into exceptions and exception handling we will learn how to create our own exceptions and how to use exceptions for program flow control when to use object-oriented programmingdeals with creating and using objects we will see how to wrap data using properties and restrict data access this also discusses the dry principle and how not to repeat code python data structurescovers the object-oriented features of python' built-in classes we'll cover tuplesdictionarieslistsand setsas well as few more advanced collections we'll also see how to extend these standard objects python object-oriented shortcutsas the name suggestsdeals with time-savers in python we will look at many useful built-in functions such as method overloading using default arguments we'll also see that functions themselves are objects and how this is useful strings and serializationlooks at stringsfilesand formatting we'll discuss the difference between stringsbytesand bytearraysas well as various ways to serialize textualobjectand binary data to several canonical representations the iterator patternintroduces us to the concept of design patterns and covers python' iconic implementation of the iterator pattern we'll learn about listsetand dictionary comprehensions we'll also demystify generators and coroutines python design patterns icovers several design patternsincluding the decoratorobserverstrategystatesingletonand template patterns each pattern is discussed with suitable examples and programs implemented in python python design patterns iiwraps up our discussion of design patterns with coverage of the adapterfacadeflyweightcommandabstractand composite patterns more examples of how idiomatic python code differs from canonical implementations are provided viii |
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 thereofof concurrency patterns it discusses threadsmultiprocessingfuturesand the new asyncio library each includes relevant examples and case study that collects the contents into working (if not completeprogram what you need for this book all the examples in this book rely on the python interpreter make sure you are not using python or earlier at the time of writingpython was the latest release of python most examples will work on earlier revisions of python but you are encouraged to use the latest version to minimize frustration all of the examples should run on any operating system supported by python if this is not the caseplease report it as bug some of the examples need working internet connection you'll probably want to have one of these for extracurricular research and debugging anywayin additionsome of the examples in this book rely on third-party libraries that do not ship with python these are introduced within the book at the time they are usedso you do not need to install them in advance howeverfor completenesshere is listpip requests pillow bitarray ix |
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 programming skills if you are familiar with object-oriented programming in other languagesthen this book will help you understand the idiomatic ways to apply your knowledge in the python ecosystem conventions this book uses variety of text styles to distinguish between different kinds of information here are some examples of these stylesand an explanation of their meaning code words in textdatabase table namesfolder namesfilenamesfile extensionspathnamesdummy urlsuser inputand twitter handles are shown as follows"we look up the class in the dictionary and store it in variable named propertyclass block of code is set as followsdef add_property(self)property_type get_valid_input"what type of property"("house""apartment")lower(payment_type get_valid_input"what payment type"("purchase""rental")lower(when we wish to draw your attention to particular part of code blockthe relevant lines or items are set in bolddef add_property(self)property_type get_valid_input"what type of property"("house""apartment")lower(payment_type get_valid_input"what payment type"("purchase""rental")lower([ |
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 dialog boxes for exampleappear in the text like this"it will fail with not enough arguments error similar to the one we received earlier when we forgot the self argument warnings or important notes appear in box like this tips and tricks appear like this reader feedback feedback from our readers is always welcome let us know what you think about this book--what you liked or disliked reader feedback is important for us as it helps us develop titles that you will really get the most out of to send us general feedbacksimply -mail feedback@packtpub comand mention the book' title in the subject of your message if there is topic that you have expertise in and you are interested in either writing or contributing to booksee our author guide at www packtpub com/authors customer support now that you are the proud owner of packt bookwe have number of things to help you to get the most from your purchase xi |
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 accuracy of our contentmistakes do happen if you find mistake in one of our books--maybe mistake in the text or the code--we would be grateful if you could report this to us by doing soyou can save other readers from frustration and help us improve subsequent versions of this book if you find any errataplease report them by visiting com/submit-errataselecting your bookclicking on the errata submission form linkand entering the details of your errata once your errata are verifiedyour submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the errata section of that title to view the previously submitted erratago to content/support and enter the name of the book in the search field the required information will appear under the errata section piracy piracy of copyrighted material on the internet is an ongoing problem across all media at packtwe take the protection of our copyright and licenses very seriously if you come across any illegal copies of our works in any form on the internetplease provide us with the location address or website name immediately so that we can pursue remedy please contact us at copyright@packtpub com with link to the suspected pirated material we appreciate your help in protecting our authors and our ability to bring you valuable content questions if you have problem with any aspect of this bookyou can contact us at questions@packtpub comand we will do our best to address the problem xii |
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 programming the basic principles of an object-oriented design basic unified modeling language (umland when it isn' evil introducing object-oriented everyone knows what an object is-- tangible thing that we can sensefeeland manipulate the earliest objects we interact with are typically baby toys wooden blocksplastic shapesand over-sized puzzle pieces are common first objects babies learn quickly that certain objects do certain thingsbells ringbuttons pressand levers pull the definition of an object in software development is not terribly different software objects are not typically tangible things that you can pick upsenseor feelbut they are models of something that can do certain things and have certain things done to them formallyan object is collection of data and associated behaviors soknowing what an object iswhat does it mean to be object-orientedoriented simply means directed toward so object-oriented means functionally directed towards modeling objects this is one of the many techniques used for modeling complex systems by describing collection of interacting objects via their data and behavior [ |
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 development calling them object-oriented simply specifies what style of software development is being pursued object-oriented analysis (ooais the process of looking at problemsystemor task (that somebody wants to turn into an applicationand identifying the objects and interactions between those objects the analysis stage is all about what needs to be done the output of the analysis stage is set of requirements if we were to complete the analysis stage in one stepwe would have turned tasksuch asi need websiteinto set of requirements for examplewebsite visitors need to be able to (italic represents actionsbold represents objects)review our history apply for jobs browsecompareand order products in some waysanalysis is misnomer the baby we discussed earlier doesn' analyze the blocks and puzzle pieces ratherit will explore its environmentmanipulate shapesand see where they might fit better turn of phrase might be object-oriented exploration in software developmentthe initial stages of analysis include interviewing customersstudying their processesand eliminating possibilities object-oriented design (oodis the process of converting such requirements into an implementation specification the designer must name the objectsdefine the behaviorsand formally specify which objects can activate specific behaviors on other objects the design stage is all about how things should be done the output of the design stage is an implementation specification if we were to complete the design stage in single stepwe would have turned the requirements defined during object-oriented analysis into set of classes and interfaces that could be implemented in (ideallyany object-oriented programming language object-oriented programming (oopis the process of converting this perfectly defined design into working program that does exactly what the ceo originally requested [ |
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 we're programmingwe find features that need clarification in the design most twenty-first century development happens in an iterative development model in iterative developmenta small part of the task is modeleddesignedand programmedthen the program is reviewed and expanded to improve each feature and include new features in series of short development cycles the rest of this book is about object-oriented programmingbut in this we will cover the basic object-oriented principles in the context of design this allows us to understand these (rather simpleconcepts without having to argue with software syntax or python interpreters objects and classes soan object is collection of data with associated behaviors how do we differentiate between types of objectsapples and oranges are both objectsbut it is common adage that they cannot be compared apples and oranges aren' modeled very often in computer programmingbut let' pretend we're doing an inventory application for fruit farm to facilitate the examplewe can assume that apples go in barrels and oranges go in baskets nowwe have four kinds of objectsapplesorangesbasketsand barrels in object-oriented modelingthe term used for kind of object is class soin technical termswe now have four classes of objects what' the difference between an object and classclasses describe objects they are like blueprints for creating an object you might have three oranges sitting on the table in front of you each orange is distinct objectbut all three have the attributes and behaviors associated with one classthe general class of oranges the relationship between the four classes of objects in our inventory system can be described using unified modeling language (invariably referred to as umlbecause three letter acronyms never go out of styleclass diagram here is our first class diagramorange basket apple barrel [ |
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 obviousyou don' have to read tutorial to (mostlyunderstand what is going on when you see one uml is also fairly easy to drawand quite intuitive after allmany peoplewhen describing classes and their relationshipswill naturally draw boxes with lines between them having standard based on these intuitive diagrams makes it easy for programmers to communicate with designersmanagersand each other howeversome programmers think uml is waste of time citing iterative developmentthey will argue that formal specifications done up in fancy uml diagrams are going to be redundant before they're implementedand that maintaining these formal diagrams will only waste time and not benefit anyone depending on the corporate structure involvedthis may or may not be true howeverevery programming team consisting of more than one person will occasionally has to sit down and hash out the details of the subsystem it is currently working on uml is extremely useful in these brainstorming sessions for quick and easy communication even those organizations that scoff at formal class diagrams tend to use some informal version of uml in their design meetings or team discussions furtherthe most important person you will ever have to communicate with is yourself we all think we can remember the design decisions we've madebut there will always be the why did do thatmoments hiding in our future if we keep the scraps of papers we did our initial diagramming on when we started designwe'll eventually find them useful reference this howeveris not meant to be tutorial in uml there are many of these available on the internetas well as numerous books available on the topic uml covers far more than class and object diagramsit also has syntax for use casesdeploymentstate changesand activities we'll be dealing with some common class diagram syntax in this discussion of object-oriented design you'll find that you can pick up the structure by exampleand you'll subconsciously choose the uml-inspired syntax in your own team or personal design sessions our initial diagramwhile correctdoes not remind us that apples go in barrels or how many barrels single apple can go in it only tells us that apples are somehow associated with barrels the association between classes is often obvious and needs no further explanationbut we have the option to add further clarification as needed [ |
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 confident that the association ismany apples go in one barrelbut just to make sure nobody confuses it withone apple spoils one barrelwe can enhance the diagram as shownorange basket go in go in apple barrel this diagram tells us that oranges go in baskets with little arrow showing what goes in what it also tells us the number of that object that can be used in the association on both sides of the relationship one basket can hold many (represented by *orange objects any one orange can go in exactly one basket this number is referred to as the multiplicity of the object you may also hear it described as the cardinality these are actually slightly distinct terms cardinality refers to the actual number of items in the setwhereas multiplicity specifies how small or how large this number could be frequently forget which side of relationship the multiplicity goes on the multiplicity nearest to class is the number of objects of that class that can be associated with any one object at the other end of the association for the apple goes in barrel associationreading from left to rightmany instances of the apple class (that is many apple objectscan go in any one barrel reading from right to leftexactly one barrel can be associated with any one apple specifying attributes and behaviors we now have grasp of some basic object-oriented terminology objects are instances of classes that can be associated with each other an object instance is specific object with its own set of data and behaviorsa specific orange on the table in front of us is said to be an instance of the general class of oranges that' simple enoughbut what are these data and behaviors that are associated with each object[ |
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 oranges on the table (if we haven' eaten anycould each weigh different amount the orange class could then have weight attribute all instances of the orange class have weight attributebut each orange has different value for this attribute attributes don' have to be uniquethoughany two oranges may weigh the same amount as more realistic exampletwo objects representing different customers might have the same value for first name attribute attributes are frequently referred to as members or properties some authors suggest that the terms have different meaningsusually that attributes are settablewhile properties are read-only in pythonthe concept of "read-onlyis rather pointlessso throughout this bookwe'll see the two terms used interchangeably in additionas we'll discuss in when to use object-oriented programmingthe property keyword has special meaning in python for particular kind of attribute orange basket +weight +orchard +date_picked +location go in go in apple barrel +color +weight +size in our fruit inventory applicationthe fruit farmer may want to know what orchard the orange came fromwhen it was pickedand how much it weighs they might also want to keep track of where each basket is stored apples might have color attributeand barrels might come in different sizes some of these properties may also belong to multiple classes (we may want to know when apples are pickedtoo)but for this first examplelet' just add few different attributes to our class diagram[ |
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 that are standard to most programming languagessuch as integerfloating-point numberstringbyteor boolean howeverthey can also represent data structures such as liststreesor graphsor most notablyother classes this is one area where the design stage can overlap with the programming stage the various primitives or objects available in one programming language may be somewhat different from what is available in other languages usuallywe don' need to be overly concerned with data types at the design stageas implementation-specific details are chosen during the programming stage generic names are normally sufficient for design if our design calls for list container typethe java programmers can choose to use linkedlist or an arraylist when implementing itwhile the python programmers (that' us!can choose between the list built-in and tuple in our fruit-farming example so farour attributes are all basic primitives howeverthere are some implicit attributes that we can make explicit--the associations for given orangewe might have an attribute containing the basket that holds that orange behaviors are actions nowwe know what data isbut what are behaviorsbehaviors are actions that can occur on an object the behaviors that can be performed on specific class of objects are called methods at the programming levelmethods are like functions in structured programmingbut they magically have access to all the data associated with this object like functionsmethods can also accept parameters and return values [ |
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 that task we've stretched our "comparing apples and orangesexample into basic (if farfetchedinventory application let' stretch it little further and see if it breaks one action that can be associated with oranges is the pick action if you think about implementationpick would place the orange in basket by updating the basket attribute of the orangeand by adding the orange to the oranges list on the basket sopick needs to know what basket it is dealing with we do this by giving the pick method basket parameter since our fruit farmer also sells juicewe can add squeeze method to orange when squeezedsqueeze might return the amount of juice retrievedwhile also removing the orange from the basket it was in basket can have sell action when basket is soldour inventory system might update some data on as-yet unspecified objects for accounting and profit calculations alternativelyour basket of oranges might go bad before we can sell themso we add discard method let' add these methods to our diagramorange basket +weightfloat +locationstring +orchardstring +orangeslist +date_pickeddate +sell(customer:customer+basketbasket +discard(+pick(basket:basket +squeeze()amount_of_juice go in adding models and methods to individual objects allows us to create system of interacting objects each object in the system is member of certain class these classes specify what types of data the object can hold and what methods can be invoked on it the data in each object can be in different state from other objects of the same classand each object may react to method calls differently because of the differences in state object-oriented analysis and design is all about figuring out what those objects are and how they should interact the next section describes principles that can be used to make those interactions as simple and intuitive as possible [ |
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 often not allowedto access the internal workings of the object common real-world example is the television our interface to the television is the remote control each button on the remote control represents method that can be called on the television object when weas the calling objectaccess these methodswe do not know or care if the television is getting its signal from an antennaa cable connectionor satellite dish we don' care what electronic signals are being sent to adjust the volumeor whether the sound is destined to speakers or headphones if we open the television to access the internal workingsfor exampleto split the output signal to both external speakers and set of headphoneswe will void the warranty this process of hiding the implementationor functional detailsof an object is suitably called information hiding it is also sometimes referred to as encapsulationbut encapsulation is actually more all-encompassing term encapsulated data is not necessarily hidden encapsulation isliterallycreating capsule and so think of creating time capsule if you put bunch of information into time capsulelock and bury itit is both encapsulated and the information is hidden on the other handif the time capsule has not been buried and is unlocked or made of clear plasticthe items inside it are still encapsulatedbut there is no information hiding the distinction between encapsulation and information hiding is largely irrelevantespecially at the design level many practical references use these terms interchangeably as python programmerswe don' actually have or need true information hiding(we'll discuss the reasons for this in objects in pythonso the more encompassing definition for encapsulation is suitable the public interfacehoweveris very important it needs to be carefully designed as it is difficult to change it in the future changing the interface will break any client objects that are calling it we can change the internals all we likefor exampleto make it more efficientor to access data over the network as well as locallyand the client objects will still be able to talk to itunmodifiedusing the public interface on the other handif we change the interface by changing attribute names that are publicly accessedor by altering the order or types of arguments that method can acceptall client objects will also have to be modified while on the topic of public interfaceskeep it simple always design the interface of an object based on how easy it is to usenot how hard it is to code (this advice applies to user interfaces as well[ |
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 details were overly complex and irrelevant before started driving the model is an abstraction of real concept abstraction is another object-oriented concept related to encapsulation and information hiding simply putabstraction means dealing with the level of detail that is most appropriate to given task it is the process of extracting public interface from the inner details driver of car needs to interact with steeringgas pedaland brakes the workings of the motordrive trainand brake subsystem don' matter to the driver mechanicon the other handworks at different level of abstractiontuning the engine and bleeding the breaks here' an example of two abstraction levels for carcar driver +brakes +gas_pedal drives +steer(+change_gears(+apply_brake(mechanic car fixes +disc_brakes +fuel_injected_engine +automatic_transmission +adjust_brake(+change_oil(nowwe have several new terms that refer to similar concepts condensing all this jargon into couple of sentencesabstraction is the process of encapsulating information with separate public and private interfaces the private interfaces can be subject to information hiding the important lesson to take from all these definitions is to make our models understandable to other objects that have to interact with them this means paying careful attention to small details ensure methods and properties have sensible names when analyzing systemobjects typically represent nouns in the original problemwhile methods are normally verbs attributes can often be picked up as adjectivesalthough if the attribute refers to another object that is part of the current objectit will still likely be noun name classesattributesand methods accordingly |
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 designs should be open ended so that future requirements can be satisfied howeverwhen abstracting interfacestry to model exactly what needs to be modeled and nothing more when designing the interfacetry placing yourself in the object' shoes and imagine that the object has strong preference for privacy don' let other objects have access to data about you unless you feel it is in your best interest for them to have it don' give them an interface to force you to perform specific task unless you are certain you want them to be able to do that to you composition so farwe learned to design systems as group of interacting objectswhere each interaction involves viewing objects at an appropriate level of abstraction but we don' know yet how to create these levels of abstraction there are variety of ways to do thiswe'll discuss some advanced design patterns in strings and serialization and the iterator pattern but even most design patterns rely on two basic object-oriented principles known as composition and inheritance composition is simplerso let' start with it composition is the act of collecting several objects together to create new one composition is usually good choice when one object is part of another object we've already seen first hint of composition in the mechanic example car is composed of an enginetransmissionstarterheadlightsand windshieldamong numerous other parts the enginein turnis composed of pistonsa crank shaftand valves in this examplecomposition is good way to provide levels of abstraction the car object can provide the interface required by driverwhile also providing access to its component partswhich offers the deeper level of abstraction suitable for mechanic those component parts canof coursebe further broken down if the mechanic needs more information to diagnose problem or tune the engine this is common introductory example of compositionbut it' not overly useful when it comes to designing computer systems physical objects are easy to break into component objects people have been doing this at least since the ancient greeks originally postulated that atoms were the smallest units of matter (theyof coursedidn' have access to particle acceleratorscomputer systems are generally less complicated than physical objectsyet identifying the component objects in such systems does not happen as naturally |
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 the physical worldbut they are all frequently-modeled components in computer systems let' try modeling more computer-oriented example to see composition in action we'll be looking at the design of computerized chess game this was very popular pastime among academics in the and people were predicting that computers would one day be able to defeat human chess master when this happened in (ibm' deep blue defeated world chess championgary kasparov)interest in the problem wanedalthough there are still contests between computer and human chess players (the computers usually win as basichigh-level analysisa game of chess is played between two playersusing chess set featuring board containing sixty-four positions in an grid the board can have two sets of sixteen pieces that can be movedin alternating turns by the two players in different ways each piece can take other pieces the board will be required to draw itself on the computer screen after each turn 've identified some of the possible objects in the description using italicsand few key methods using bold this is common first step in turning an object-oriented analysis into design at this pointto emphasize compositionwe'll focus on the boardwithout worrying too much about the players or the different types of pieces let' start at the highest level of abstraction possible we have two players interacting with chess set by taking turns making movesmake_move chess set player make_move player |
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 members of the same classso the class diagram looks little differentplayer chess set make move the diagram shows that exactly two players can interact with one chess set it also indicates that any one player can be playing with only one chess set at time howeverwe're discussing compositionnot umlso let' think about what the chess set is composed of we don' care what the player is composed of at this time we can assume that the player has heart and brainamong other organsbut these are irrelevant to our model indeedthere is nothing stopping said player from being deep blue itselfwhich has neither heart nor brain the chess setthenis composed of board and pieces the board further comprises positions you could argue that pieces are not part of the chess set because you could replace the pieces in chess set with different set of pieces while this is unlikely or impossible in computerized version of chessit introduces us to aggregation aggregation is almost exactly like composition the difference is that aggregate objects can exist independently it would be impossible for position to be associated with different chess boardso we say the board is composed of positions but the pieceswhich might exist independently of the chess setare said to be in an aggregate relationship with that set another way to differentiate between aggregation and composition is to think about the lifespan of the object if the composite (outsideobject controls when the related (insideobjects are created and destroyedcomposition is most suitable if the related object is created independently of the composite objector can outlast that objectan aggregate relationship makes more sense alsokeep in mind that composition is aggregationaggregation is simply more general form of composition any composite relationship is also an aggregate relationshipbut not vice versa |
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 as solid diamond the hollow diamond represents the aggregate relationship you'll notice that the board and pieces are stored as part of the chess set in exactly the same way reference to them is stored as an attribute on the chess set this shows thatonce againin practicethe distinction between aggregation and composition is often irrelevant once you get past the design stage when implementedthey behave in much the same way howeverit can help to differentiate between the two when your team is discussing how the different objects interact oftenyou can treat them as the same thingbut when you need to distinguish between themit' great to know the difference (this is abstraction at workinheritance we discussed three types of relationships between objectsassociationcompositionand aggregation howeverwe have not fully specified our chess setand these tools don' seem to give us all the power we need we discussed the possibility that player might be human or it might be piece of software featuring artificial intelligence it doesn' seem right to say that player is associated with humanor that the artificial intelligence implementation is part of the player object what we really need is the ability to say that "deep blue is playeror that "gary kasparov is playerthe is relationship is formed by inheritance inheritance is the most famouswellknownand over-used relationship in object-oriented programming inheritance is sort of like family tree my grandfather' last name was phillips and my father inherited that name inherited it from him (along with blue eyes and penchant for writingin object-oriented programminginstead of inheriting features and behaviors from personone class can inherit attributes and methods from another class |
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 drawn on the chess boardand make different moves let' see how the six types of pieces can inherit from piece classpawn rook +shape +shape piece +move(board+move(board+chess_setchessset +color bishop queen +shape +shape +move(board+move(boardknight king +shape +shape +move(board+move(boardthe hollow arrows indicate that the individual classes of pieces inherit from the piece class all the subtypes automatically have chess_set and color attribute inherited from the base class each piece provides different shape property (to be drawn on the screen when rendering the board)and different move method to move the piece to new position on the board at each turn we actually know that all subclasses of the piece class need to have move methodotherwisewhen the board tries to move the pieceit will get confused it is possible that we would want to create new version of the game of chess that has one additional piece (the wizardour current design allows us to design this piece without giving it move method the board would then choke when it asked the piece to move itself we can implement this by creating dummy move method on the piece class the subclasses can then override this method with more specific implementation the default implementation mightfor examplepop up an error message that saysthat piece cannot be moved |
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 direction and move it accordingly we could then override this method in subclass with the deep blue implementation the first class would be suitable for play against raw beginnerthe latter would challenge grand master the important thing is that other methods in the classsuch as the ones that inform the board as to which move was chose need not be changedthis implementation can be shared between the two classes in the case of chess piecesit doesn' really make sense to provide default implementation of the move method all we need to do is specify that the move method is required in any subclasses this can be done by making piece an abstract class with the move method declared abstract abstract methods basically say"we demand this method exist in any non-abstract subclassbut we are declining to specify an implementation in this class indeedit is possible to make class that does not implement any methods at all such class would simply tell us what the class should dobut provides absolutely no advice on how to do it in object-oriented parlancesuch classes are called interfaces inheritance provides abstraction let' explore the longest word in object-oriented argot polymorphism is the ability to treat class differently depending on which subclass is implemented we've already seen it in action with the pieces system we've described if we took the design bit furtherwe' probably see that the board object can accept move from the player and call the move function on the piece the board need not ever know what type of piece it is dealing with all it has to do is call the move methodand the proper subclass will take care of moving it as knight or pawn polymorphism is pretty coolbut it is word that is rarely used in python programming python goes an extra step past allowing subclass of an object to be treated like parent class board implemented in python could take any object that has move methodwhether it is bishop piecea caror duck when move is calledthe bishop will move diagonally on the boardthe car will drive someplaceand the duck will swim or flydepending on its mood |
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 create new types of birds without actually specifying an inheritance hierarchy for aquatic birds it also allows them to create completely different drop-in behaviors that the original designers never planned for for examplefuture designers might be able to make walkingswimming penguin that works with the same interface without ever suggesting that penguins are ducks multiple inheritance when we think of inheritance in our own family treewe can see that we inherit features from more than just one parent when strangers tell proud mother that her son has"his fathers eyes"she will typically respond along the lines of"yesbut he got my nose object-oriented design can also feature such multiple inheritancewhich allows subclass to inherit functionality from multiple parent classes in practicemultiple inheritance can be tricky businessand some programming languages (most notablyjavastrictly prohibit it howevermultiple inheritance can have its uses most oftenit can be used to create objects that have two distinct sets of behaviors for examplean object designed to connect to scanner and send fax of the scanned document might be created by inheriting from two separate scanner and faxer objects as long as two classes have distinct interfacesit is not normally harmful for subclass to inherit from both of them howeverit gets messy if we inherit from two classes that provide overlapping interfaces for exampleif we have motorcycle class that has move methodand boat class also featuring move methodand we want to merge them into the ultimate amphibious vehiclehow does the resulting class know what to do when we call moveat the design levelthis needs to be explainedand at the implementation leveleach programming language has different ways of deciding which parent class' method is calledor in what order oftenthe best way to deal with it is to avoid it if you have design showing up like thisyou're probably doing it wrong take step backanalyze the system againand see if you can remove the multiple inheritance relationship in favor of some other association or composite design |
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 nails inheritance is the perfect solution for obvious is relationshipsbut it can be abused programmers often use inheritance to share code between two kinds of objects that are only distantly relatedwith no is relationship in sight while this is not necessarily bad designit is terrific opportunity to ask just why they decided to design it that wayand whether different relationship or design pattern would have been more suitable case study let' tie all our new object-oriented knowledge together by going through few iterations of object-oriented design on somewhat real-world example the system we'll be modeling is library catalog libraries have been tracking their inventory for centuriesoriginally using card catalogsand more recentlyelectronic inventories modern libraries have web-based catalogs that we can query from our homes let' start with an analysis the local librarian has asked us to write new card catalog program because their ancient dos-based program is ugly and out of date that doesn' give us much detailbut before we start asking for more informationlet' consider what we already know about library catalogs catalogs contain lists of books people search them to find books on certain subjectswith specific titlesor by particular author books can be uniquely identified by an international standard book number (isbneach book has dewey decimal system (ddsnumber assigned to help find it on particular shelf this simple analysis tells us some of the obvious objects in the system we quickly identify book as the most important objectwith several attributes already mentionedsuch as authortitlesubjectisbnand dds numberand catalog as sort of manager for books we also notice few other objects that may or may not need to be modeled in the system for cataloging purposesall we need to search book by author is an author_ name attribute on the book howeverauthors are also objectsand we might want to store some other data about the author as we ponder thiswe might remember that some books have multiple authors suddenlythe idea of having single author_name attribute on objects seems bit silly list of authors associated with each book is clearly better idea |
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 should also pay attention to the noun (nouns are always good candidates for objectsshelf is shelf an object that needs to be modeled in cataloging systemhow do we identify an individual shelfwhat happens if book is stored at the end of one shelfand later moved to the beginning of the next shelf because another book was inserted in the previous shelfdds was designed to help locate physical books in library as suchstoring dds attribute with the book should be enough to locate itregardless of which shelf it is stored on so we canat least for the momentremove shelf from our list of contending objects another questionable object in the system is the user do we need to know anything about specific usersuch as their nameaddressor list of overdue booksso farthe librarian has told us only that they want catalogthey said nothing about tracking subscriptions or overdue notices in the back of our mindswe also note that authors and users are both specific kinds of peoplethere might be useful inheritance relationship here in the future for cataloging purposeswe decide we don' need to identify the user for now we can assume that user will be searching the catalogbut we don' have to actively model them in the systembeyond providing an interface that allows them to search we have identified few attributes on the bookbut what properties does catalog havedoes any one library have more than one catalogdo we need to uniquely identify themobviouslythe catalog has to have collection of the books it containssomehowbut this list is probably not part of the public interface what about behaviorsthe catalog clearly needs search methodpossibly separate ones for authorstitlesand subjects are there any behaviors on bookswould it need preview methodor could preview be identified by first pages attribute instead of methodthe questions in the preceding discussion are all part of the object-oriented analysis phase but intermixed with the questionswe have already identified few key objects that are part of the design indeedwhat you have just seen are several microiterations between analysis and design |
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 interactively improve itwe meet up with the librarian they tell us that this is good startbut libraries don' serve only booksthey also have dvdsmagazinesand cdsnone of which have an isbn or dds number all of these types of items can be uniquely identified by upc number though we remind the librarian that they have to find the items on the shelfand these items probably aren' organized by upc the librarian explains that each type is organized in different way the cds are mostly audio booksand they only have couple of dozen in stockso they are organized by the author' last name dvds are divided into genre and further organized by title magazines are organized by title and then refined by the volume and issue number books areas we had guessedorganized by the dds number with no previous object-oriented design experiencewe might consider adding separate lists of dvdscdsmagazinesand books to our catalogand search each one in turn the trouble isexcept for certain extended attributesand identifying the physical location of the itemthese items all behave as much the same this is job for inheritancewe quickly update our uml diagramlibraryitem catalog +search( +title +upc +subject +locate(book author +name +isbn +authors +title +subject +dds number magazine +volume +issue dvd cd +actors +director +genre +artist |
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 "bunniesin the title at this pointthe catalog doesn' care if it is holding dvdbookcdor magazineall items are the sameas far as the catalog is concerned howeverthe user wants to know how to find the physical itemsso the catalog would be remiss if it simply returned list of titles soit calls the locate method on the two items it has uncovered the book' locate method returns dds number that can be used to find the shelf holding the book the dvd is located by returning the genre and title of the dvd the user can then visit the dvd sectionfind the section containing that genreand find the specific dvd as sorted by the titles as we explainwe sketch uml sequence diagram explaining how the various objects are communicatingcatalog bunnies book bunnies dvd user search locate dds number locate genretitle results whereclass diagrams describe the relationships between classesand sequence diagrams describe specific sequences of messages passed between objects the dashed line hanging from each object is lifeline describing the lifetime of the object the wider boxes on each lifeline represent active processing in that object (where there' no boxthe object is basically sitting idlewaiting for something to happenthe horizontal arrows between the lifelines indicate specific messages the solid arrows represent methods being calledwhile the dashed arrows with solid heads represent the method return values |
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 callswhich do the processing in the methodand return value immediately sequence diagramslike all uml diagramsare best used only when they are needed there is no point in drawing uml diagram for the sake of drawing diagram howeverwhen you need to communicate series of interactions between two objectsthe sequence diagram is very useful tool unfortunatelyour class diagram so far is still messy design we notice that actors on dvds and artists on cds are all types of peoplebut are being treated differently from the book authors the librarian also reminds us that most of their cds are audio bookswhich have authors instead of artists how can we deal with different kinds of people that contribute to titlean obvious implementation is to create person class with the person' name and other relevant detailsand then create subclasses of this for the artistsauthorsand actors howeveris inheritance really necessary herefor searching and cataloging purposeswe don' really care that acting and writing are two very different activities if we were doing an economic simulationit would make sense to give separate actor and author classesand different calculate_income and perform_job methodsbut for cataloging purposesit is probably enough to know how the person contributed to the item we recognize that all items have one or more contributor objectsso we move the author relationship from the book to its parent classlibraryitem catalog +search( +title +upc +subject +contributors contributor +name +locate(book +isbn +title +subject +dds number cd dvd magazine +genre +volume +issue |
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 library items this little changewhile it looks bit cleaner and simplerhas lost some vital information we can still tell who contributed to specific library itembut we don' know how they contributed were they the director or an actordid they write the audio bookor were they the voice that narrated the bookit would be nice if we could just add contributor_type attribute on the contributor classbut this will fall apart when dealing with multitalented people who have both authored books and directed movies one option is to add attributes to each of our libraryitem subclasses that hold the information we needsuch as author on bookor artist on cdand then make the relationship to those properties all point to the contributor class the problem with this is that we lose lot of polymorphic elegance if we want to list the contributors to an itemwe have to look for specific attributes on that itemsuch as authors or actors we can alleviate this by adding getcontributors method on the libraryitem class that subclasses can override then the catalog never has to know what attributes the objects are queryingwe've abstracted the public interfacelibraryitem catalog +search( +title +upc +subject +contributors +locate(+getcontributors(book +isbn +title +subject +dds number +authors cd magazine dvd +genre +actors +directors +volume +issue +editors contributor +name +artists |
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 meatballs now that we've explored inheritance as an optionand found it wantingwe might look back at our previous composition-based diagramwhere contributor was attached directly to libraryitem with some thoughtwe can see that we actually only need to add one more relationship to brand-new class to identify the type of contributor this is an important step in object-oriented design we are now adding class to the design that is intended to support the other objectsrather than modeling any part of the initial requirements we are refactoring the design to facilitate the objects in the systemrather than objects in real life refactoring is an essential process in the maintenance of program or design the goal of refactoring is to improve the design by moving code aroundremoving duplicate code or complex relationships in favor of simplermore elegant designs this new class is composed of contributor and an extra attribute identifying the type of contribution the person has made to the given libraryitem there can be many such contributions to particular libraryitemand one contributor can contribute in the same way to different items the diagram communicates this design very welllibraryitem catalog +search(+title +upc +subject +contributors contributorwithtype +contributor +type +locate(contributor +name book +isbn +title +subject +dds number magazine cd dvd +genre +volume +issue |
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 or changing attributes or behaviors on the subclass to make it somehow different from the parent class it seems silly to create bunch of empty classes solely for identifying different types of objects (this attitude is less prevalent among java and other "everything is an objectprogrammersbut it is common among more practical python designersif we look at the inheritance version of the diagramwe can see bunch of subclasses that don' actually do anythingauthor actor libraryitem +title +upc +subject +contributors contributor +name director +locate(artist editor sometimes it is important to recognize when not to use object-oriented principles this example of when not to use inheritance is good reminder that objects are just toolsand not rules exercises this is practical booknot textbook as suchi' not about to assign you bunch of fake object-oriented analysis problems to create designs for bunch of fake object-oriented problems to analyze and design insteadi want to give you some thoughts that you can apply to your own projects if you have previous objectoriented experienceyou won' need to put much effort into these howeverthey are useful mental exercises if you've been using python for whilebut never really cared about all that class stuff |
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 attributes actually behaviors in disguisesometimes what looks like data is actually calculated from other data on the objectand you can use method to do those calculations what other methods or behaviors did the object havewhich objects called those methodswhat kinds of relationships did they have with this objectnowthink about an upcoming project it doesn' matter what the project isit might be fun free-time project or multimillion dollar contract it doesn' have to be complete applicationit could just be one subsystem perform basic object-oriented analysis identify the requirements and the interacting objects sketch out class diagram featuring the highest level of abstraction on that system identify the major interacting objects identify minor supporting objects go into detail for the attributes and methods of some of the most interesting ones take different objects to different levels of abstraction look for places you can use inheritance or composition look for places you should avoid inheritance the goal is not to design system (although you're certainly welcome to do so if inclination meets both ambition and available timethe goal is to think about objectoriented designs focusing on projects that you have worked onor are expecting to work on in the futuresimply makes it real nowvisit your favorite search engine and look up some tutorials on uml there are dozensso find the one that suits your preferred method of study sketch some class diagrams or sequence diagram for the objects you identified earlier don' get too hung up on memorizing the syntax (after allif it is importantyou can always look it up again)just get feel for the language something will stay lodged in your brainand it can make communicating bit easier if you can quickly sketch diagram for your next oop discussion summary in this we took whirlwind tour through the terminology of the objectoriented paradigmfocusing on object-oriented design we can separate different objects into taxonomy of different classes and describe the attributes and behaviors of those objects via the class interface classes describe objectsabstractionencapsulationand information hiding are highly related concepts there are many different kinds of relationships between objectsincluding associationcompositionand inheritance uml syntax can be useful for fun and communication in the next we'll explore how to implement classes and methods in python |
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-oriented software after completing this we will understandhow to create classes and instantiate objects in python how to add attributes and behaviors to python objects how to organize classes into packages and modules how to suggest people don' clobber our data creating python classes we don' have to write much python code to realize that python is very "cleanlanguage when we want to do somethingwe just do itwithout having to go through lot of setup the ubiquitous "hello worldin pythonas you've likely seenis only one line similarlythe simplest class in python looks like thisclass myfirstclasspass there' our first object-oriented programthe class definition starts with the class keyword this is followed by name (of our choiceidentifying the classand is terminated with colon |
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 subsequent words should also start with capitalthe class definition line is followed by the class contents indented as with other python constructsindentation is used to delimit the classesrather than braces or brackets as many other languages use use four spaces for indentation unless you have compelling reason not to (such as fitting in with somebody else' code that uses tabs for indentsany decent programming editor can be configured to insert four spaces whenever the tab key is pressed since our first class doesn' actually do anythingwe simply use the pass keyword on the second line to indicate that no further action needs to be taken we might think there isn' much we can do with this most basic classbut it does allow us to instantiate objects of that class we can load the class into the python interpreterso we can interactively play with it to do thissave the class definition mentioned earlier into file named first_class py and then run the command python - first_class py the - argument tells python to "run the code and then drop to the interactive interpreterthe following interpreter session demonstrates basic interaction with this classa myfirstclass( myfirstclass(print(aprint(bthis code instantiates two objects from the new classnamed and creating an instance of class is simple matter of typing the class name followed by pair of parentheses it looks much like normal function callbut python knows we're "callinga class and not functionso it understands that its job is to create new object when printedthe two objects tell us which class they are and what memory address they live at memory addresses aren' used much in python codebut herethey demonstrate that there are two distinct objects involved |
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 doesn' contain any dataand it doesn' do anything what do we have to do to assign an attribute to given objectit turns out that we don' have to do anything special in the class definition we can set arbitrary attributes on an instantiated object using the dot notationclass pointpass point( point( print( xp yprint( xp yif we run this codethe two print statements at the end tell us the new attribute values on the two objects this code creates an empty point class with no data or behaviors then it creates two instances of that class and assigns each of those instances and coordinates to identify point in two dimensions all we need to do to assign value to an attribute on an object is use the syntax this is sometimes referred to as dot notation the value can be anythinga python primitivea built-in data typeor another object it can even be function or another class |
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 we can start with called reset that moves the point to the origin (the origin is the point where and are both zerothis is good introductory action because it doesn' require any parametersclass pointdef reset(self)self self point( reset(print( xp ythis print statement shows us the two zeros on the attributes method in python is formatted identically to function it starts with the keyword def followed by space and the name of the method this is followed by set of parentheses containing the parameter list (we'll discuss that self parameter in just moment)and terminated with colon the next line is indented to contain the statements inside the method these statements can be arbitrary python code operating on the object itself and any parameters passed in as the method sees fit talking to yourself the one difference between methods and normal functions is that all methods have one required argument this argument is conventionally named selfi've never seen programmer use any other name for this variable (convention is very powerful thingthere' nothing stopping youhoweverfrom calling it this or even martha the self argument to method is simply reference to the object that the method is being invoked on we can access attributes and methods of that object as if it were any another object this is exactly what we do inside the reset method when we set the and attributes of the self object |
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 calling the method on the objectwe can invoke the function on the classexplicitly passing our object as the self argumentp point(point reset(pprint( xp ythe output is the same as the previous example because internallythe exact same process has occurred what happens if we forget to include the self argument in our class definitionpython will bail with an error messageclass pointdef reset()pass point( reset(traceback (most recent call last)file ""line in typeerrorreset(takes no arguments ( giventhe error message is not as clear as it could be ("you silly foolyou forgot the self argumentwould be more informativejust remember that when you see an error message that indicates missing argumentsthe first thing to check is whether you forgot self in the method definition more arguments sohow do we pass multiple arguments to methodlet' add new method that allows us to move point to an arbitrary positionnot just to the origin we can also include one that accepts another point object as input and returns the distance between themimport math class point |
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(point )point move( , print(point calculate_distance(point )print(point calculate_distance(point )the print statements at the end give us the following output lot has happened here the class now has three methods the move method accepts two argumentsx and yand sets the values on the self objectmuch like the old reset method from the previous example the old reset method now calls movesince reset is just move to specific known location the calculate_distance method uses the not-too-complex pythagorean theorem to calculate the distance between two points hope you understand the math (*means squaredand math sqrt calculates square root)but it' not requirement for our current focuslearning how to write methods |
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 assert function is simple test toolthe program will bail if the statement after assert is false (or zeroemptyor nonein this casewe use it to ensure that the distance is the same regardless of which point called the other point' calculate_ distance method initializing the object if we don' explicitly set the and positions on our point objecteither using move or by accessing them directlywe have broken point with no real position what will happen when we try to access itwelllet' just try it and see "try it and seeis an extremely useful tool for python study open up your interactive interpreter and type away the following interactive session shows what happens if we try to access missing attribute if you saved the previous example as file or are using the examples distributed with the bookyou can load it into the python interpreter with the command python - filename pypoint point(point print(point print(point ytraceback (most recent call last)file ""line in attributeerror'pointobject has no attribute 'ywellat least it threw useful exception we'll cover exceptions in detail in expecting the unexpected you've probably seen them before (especially the ubiquitous syntaxerrorwhich means you typed something incorrectly!at this pointsimply be aware that it means something went wrong the output is useful for debugging in the interactive interpreterit tells us the error occurred at line which is only partially true (in an interactive sessiononly one line is executed at timeif we were running script in fileit would tell us the exact line numbermaking it easy to find the offending code in additionit tells us the error is an attributeerrorand gives helpful message telling us what that error means |
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 programming languages have the concept of constructora special method that creates and initializes the object when it is created python is little differentit has constructor and an initializer the constructor function is rarely used unless you're doing something exotic sowe'll start our discussion with the initialization method the python initialization method is the same as any other methodexcept it has special name__init__ the leading and trailing double underscores mean this is special method that the python interpreter will treat as special case never name function of your own with leading and trailing double underscores it may mean nothing to pythonbut there' always the possibility that the designers of python will add function that has special purpose with that name in the futureand when they doyour code will break let' start with an initialization function on our point class that requires the user to supply and coordinates when the point object is instantiatedclass pointdef __init__(selfxy)self move(xydef move(selfxy)self self def reset(self)self move( constructing point point point( print(point xpoint ynowour point can never go without coordinateif we try to construct point without including the proper initialization parametersit will fail with not enough arguments error similar to the one we received earlier when we forgot the self argument |
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 variables will still be available to the functionbut they will have the values specified in the argument list here' an exampleclass pointdef __init__(selfx= = )self move(xymost of the timewe put our initialization statements in an __init__ function but as mentioned earlierpython has constructor in addition to its initialization function you may never need to use the other python constructorbut it helps to know it existsso we'll cover it briefly the constructor function is called __new__ as opposed to __init__and accepts exactly one argumentthe class that is being constructed (it is called before the object is constructedso there is no self argumentit also has to return the newly created object this has interesting possibilities when it comes to the complicated art of metaprogrammingbut is not very useful in day-to-day programming in practiceyou will rarelyif everneed to use __new__ and __init__ will be sufficient explaining yourself python is an extremely easy-to-read programming languagesome might say it is self-documenting howeverwhen doing object-oriented programmingit is important to write api documentation that clearly summarizes what each object and method does keeping documentation up-to-date is difficultthe best way to do it is to write it right into our code python supports this through the use of docstrings each classfunctionor method header can have standard python string as the first line following the definition (the line that ends in colonthis line should be indented the same as the following code docstrings are simply python strings enclosed with apostrophe ('or quote ("characters oftendocstrings are quite long and span multiple lines (the style guide suggests that the line length should not exceed characters)which can be formatted as multi-line stringsenclosed in matching triple apostrophe ('''or triple quote ("""characters |
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 should also be noted to illustrate the use of docstringswe will end this section with our completely documented point classimport math class point'represents point in two-dimensional geometric coordinatesdef __init__(selfx= = )'''initialize the position of new point the and coordinates can be specified if they are notthe point defaults to the origin ''self move(xydef move(selfxy)"move the point to new location in space self self def reset(self)'reset the point back to the geometric origin self move( def calculate_distance(selfother_point)"""calculate the distance from this point to second point passed as parameter this function uses the pythagorean theorem to calculate the distance between the two points the distance is returned as float ""return math sqrt(self other_point )** (self other_point )** |
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 do we organize themfor small programswe can just put all our classes into one file and add little script at the end of the file to start them interacting howeveras our projects growit can become difficult to find the one class that needs to be edited among the many classes we've defined this is where modules come in modules are simply python filesnothing more the single file in our small program is module two python files are two modules if we have two files in the same folderwe can load class from one module for use in the other module for exampleif we are building an -commerce systemwe will likely be storing lot of data in database we can put all the classes and functions related to database access into separate file (we'll call it something sensibledatabase pythenour other modules (for examplecustomer modelsproduct informationand inventorycan import classes from that module in order to access the database |
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 assume we have module called database py that contains class called databaseand second module called products py that is responsible for product-related queries at this pointwe don' need to think too much about the contents of these files what we know is that products py needs to instantiate the database class from database py so that it can execute queries on the product table in the database there are several variations on the import statement syntax that can be used to access the classimport database db database database(do queries on db this version imports the database module into the products namespace (the list of names currently accessible in module or function)so any class or function in the database module can be accessed using the database notation alternativelywe can import just the one class we need using the from import syntaxfrom database import database db database(do queries on db iffor some reasonproducts already has class called databaseand we don' want the two names to be confusedwe can rename the class when used inside the products modulefrom database import database as db db db(do queries on db we can also import multiple items in one statement if our database module also contains query classwe can import both classes usingfrom database import databasequery |
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 much sense to beginners one way to learn why to avoid this syntax is to use it and try to understand your code two years later but we can save some time and two years of poorly written code with quick explanation nowwhen we explicitly import the database class at the top of our file using from database import databasewe can easily see where the database class comes from we might use db database( lines later in the fileand we can quickly look at the imports to see where that database class came from thenif we need clarification as to how to use the database classwe can visit the original file (or import the module in the interactive interpreter and use the help(database databasecommandhoweverif we use the from database import syntaxit takes lot longer to find where that class is located code maintenance becomes nightmare in additionmost editors are able to provide extra functionalitysuch as reliable code completionthe ability to jump to the definition of classor inline documentationif normal imports are used the import syntax usually completely destroys their ability to do this reliably finallyusing the import syntax can bring unexpected objects into our local namespace sureit will import all the classes and functions defined in the module being imported frombut it will also import any classes or modules that were themselves imported into that fileevery name used in module should come from well-specified placewhether it is defined in that moduleor explicitly imported from another module there should be no magic variables that seem to come out of thin air we should always be able to immediately identify where the names in our current namespace originated promise that if you use this evil syntaxyou will one day have extremely frustrating moments of "where on earth can this class be coming from? |
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 fileshowevercan go in folders and so can modules package is collection of modules in folder the name of the package is the name of the folder all we need to do to tell python that folder is package is place (normally emptyfile in the folder named __init__ py if we forget this filewe won' be able to import modules from that folder let' put our modules inside an ecommerce package in our working folderwhich will also contain main py file to start the program let' additionally add another package in the ecommerce package for various payment options the folder hierarchy will look like thisparent_directorymain py ecommerce__init__ py database py products py payments__init__ py square py stripe py when importing modules or classes between packageswe have to be cautious about the syntax in python there are two ways of importing modulesabsolute imports and relative imports absolute imports absolute imports specify the complete path to the modulefunctionor path we want to import if we need access to the product class inside the products modulewe could use any of these syntaxes to do an absolute importimport ecommerce products product ecommerce products product(or from ecommerce products import product product product( |
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 the packages are available to pythonit will be able to import them for examplethe packages can also be installed to the python site packages folderor the pythonpath environment variable could be customized to dynamically tell python what folders to search for packages and modules it is going to import sowith these choiceswhich syntax do we chooseit depends on your personal taste and the application at hand if there are dozens of classes and functions inside the products module that want to usei generally import the module name using the from ecommerce import products syntaxand then access the individual classes using products product if only need one or two classes from the products modulei can import them directly using the from ecommerce proucts import product syntax don' personally use the first syntax very often unless have some kind of name conflict (for examplei need to access two completely different modules called products and need to separate themdo whatever you think makes your code look more elegant relative imports when working with related modules in packageit seems kind of silly to specify the full pathwe know what our parent module is named this is where relative imports come in relative imports are basically way of saying find classfunctionor module as it is positioned relative to the current module for exampleif we are working in the products module and we want to import the database class from the database module next to itwe could use relative importfrom database import database the period in front of database says "use the database module inside the current packagein this casethe current package is the package containing the products py file we are currently editingthat isthe ecommerce package if we were editing the paypal module inside the ecommerce payments packagewe would want to say "use the database package inside the parent packageinstead this is easily done with two periodsas shown herefrom database import database |
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_mail function into our paypal modulefrom contact email import send_mail this import uses two periods to saythe parent of the payments packageand then uses the normal package module syntax to go back up into the contact package finallywe can import code directly from packagesas opposed to just modules inside packages in this examplewe have an ecommerce package containing two modules named database py and products py the database module contains db variable that is accessed from lot of places wouldn' it be convenient if this could be imported as import ecommerce db instead of import ecommerce database dbremember the __init__ py file that defines directory as packagethis file can contain any variable or class declarations we likeand they will be available as part of the package in our exampleif the ecommerce/__init__ py file contained this linefrom database import db we can then access the db attribute from main py or any other file using this importfrom ecommerce import db it might help to think of the __init__ py file as if it was an ecommerce py file if that file were module instead of package this can also be useful if you put all your code in single module and later decide to break it up into package of modules the __init__ py file for the new package can still be the main point of contact for other modules talking to itbut the code can be internally organized into several different modules or subpackages recommend not putting all your code in an __init__ py filethough programmers do not expect actual logic to happen in this fileand much like with from import *it can trip them up if they are looking for the declaration of particular piece of code and can' find it until they check __init__ py |
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 database object globally available from the database module the database module might look like thisclass databasethe database implementation pass database database(then we can use any of the import methods we've discussed to access the database objectfor examplefrom ecommerce database import database problem with the preceding class is that the database object is created immediately when the module is first importedwhich is usually when the program starts up this isn' always ideal since connecting to database can take whileslowing down startupor the database connection information may not yet be available we could delay creating the database until it is actually needed by calling an initialize_database function to create the module-level variableclass databasethe database implementation pass database none def initialize_database()global database database database(the global keyword tells python that the database variable inside initialize_ database is the module level one we just defined if we had not specified the variable as globalpython would have created new local variable that would be discarded when the method exitsleaving the module-level value unchanged |
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 -commerce examplethat perform execution oftenwe will write program that does something usefuland then later find that we want to import function or class from that module in different program howeveras soon as we import itany code at the module level is immediately executed if we are not carefulwe can end up running the first program when we really only meant to access couple functions inside that module to solve thiswe should always put our startup code in function (conventionallycalled mainand only execute that function when we know we are running the module as scriptbut not when our code is being imported from different script but how do we know thisclass usefulclass'''this class might be useful to other modules ''pass def main()'''creates useful class and does something with it for our module ''useful usefulclass(print(usefulif __name__ ="__main__"main(every module has __name__ special variable (rememberpython uses double underscores for special variablessuch as class' __init__ methodthat specifies the name of the module when it was imported when the module is executed directly with python module pyit is never importedso the __name__ is arbitrarily set to the string "__main__make it policy to wrap all your scripts in an if __name__ ="__main__"testjust in case you write function you will find useful to be imported by other code someday somethods go in classeswhich go in moduleswhich go in packages is that all there is to it |
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 objectwhich is expected to have format(method that accepts string ''class defaultformatter'''format string in title case ''def format(selfstring)return str(stringtitle(if not formatterformatter defaultformatter(return formatter format(stringhello_string "hello worldhow are you today?print(inputhello_stringprint("outputformat_string(hello_string)the output will be as followsinputhello worldhow are you todayoutputhello worldhow are you todaythe format_string function accepts string and optional formatter objectand then applies the formatter to that string if no formatter is suppliedit creates formatter of its own as local class and instantiates it since it is created inside the scope of the functionthis class cannot be accessed from anywhere outside of that function similarlyfunctions can be defined inside other functions as wellin generalany python statement can be executed at any time these inner classes and functions are occasionally useful for one-off items that don' require or deserve their own scope at the module levelor only make sense inside single method howeverit is not common to see python code that frequently uses this technique |
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 are publicmeaning any other object is allowed to access them python doesn' do this python doesn' really believe in enforcing laws that might someday get in your way insteadit provides unenforced guidelines and best practices technicallyall methods and attributes on class are publicly available if we want to suggest that method should not be used publiclywe can put note in docstrings indicating that the method is meant for internal use only (preferablywith an explanation of how the public-facing api works!by conventionwe should also prefix an attribute or method with an underscore character_ python programmers will interpret this as "this is an internal variablethink three times before accessing it directlybut there is nothing inside the interpreter to stop them from accessing it if they think it is in their best interest to do so because if they think sowhy should we stop themwe may not have any idea what future uses our classes may be put to there' another thing you can do to strongly suggest that outside objects don' access property or methodprefix it with double underscore__ this will perform name mangling on the attribute in question this basically means that the method can still be called by outside objects if they really want to do itbut it requires extra work and is strong indicator that you demand that your attribute remains private for exampleclass secretstring''' not-at-all secure way to store secret string ''def __init__(selfplain_stringpass_phrase)self __plain_string plain_string self __pass_phrase pass_phrase def decrypt(selfpass_phrase)'''only show the string if the pass_phrase is correct ''if pass_phrase =self __pass_phrasereturn self __plain_string elsereturn ' |
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 attributeerror'secretstringobject has no attribute '__plain_textit looks like it worksnobody can access our plain_text attribute without the passphraseso it must be safe before we get too excitedthoughlet' see how easy it can be to hack our securityprint(secret_string _secretstring__plain_stringacmetop secret oh nosomebody has hacked our secret string good thing we checkedthis is python name mangling at work when we use double underscorethe property is prefixed with when methods in the class internally access the variablethey are automatically unmangled when external classes wish to access itthey have to do the name mangling themselves soname mangling does not guarantee privacyit only strongly recommends it most python programmers will not touch double underscore variable on another object unless they have an extremely compelling reason to do so howevermost python programmers will not touch single underscore variable without compelling reason either thereforethere are very few good reasons to use name-mangled variable in pythonand doing so can cause grief for examplea name-mangled variable may be useful to subclassand it would have to do the mangling itself let other objects access your hidden information if they want tojust let them knowusing single-underscore prefix or some clear docstringsthat you think this is not good idea |
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' code we won' be covering the details about turning your packages into librariesbut if you have problem you need to solve and you don' feel like coding it (the best programmers are extremely lazy and prefer to reuse existingproven coderather than write their own)you can probably find the library you want on the python package index (pypiat you want to installyou can use tool called pip to install it howeverpip does not come with pythonbut python contains useful tool called ensurepipwhich will install itpython - ensurepip this may fail for you on linuxmac osor other unix systemsin which caseyou'll need to become root to make it work on most modern unix systemsthis can be done with sudo python - ensurepip if you are using an older version of python than python you'll need to download and install pip yourselfsince ensurepip doesn' exist you can do this by following the instructions at readthedocs orgonce pip is installed and you know the name of the package you want to installyou can install it using syntax such aspip install requests howeverif you do thisyou'll either be installing the third-party library directly into your system python directoryor more likelyget an error that you don' have permission to do so you could force the installation as an administratorbut common consensus in the python community is that you should only use system installers to install the third-party library to your system python directory |
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 system python at all here' how to use itcd project_directory python - venv env source env/bin/activate on linux or macos env/bin/activate bat on windows typicallyyou'll create different virtual environment for each python project you work on you can store your virtual environments anywherebut keep mine in the same directory as the rest of my project files (but ignored in version control)so first we cd into that directory then we run the venv utility to create virtual environment named env finallywe use one of the last two lines (depending on the operating systemas indicated in the commentsto activate the environment we'll need to execute this line each time we want to use that particular virtualenvand then use the command deactivate when we are done working on this project virtual environments are terrific way to keep your third-party dependencies separate it is common to have different projects that depend on different versions of particular library (for examplean older website might run on django while newer versions run on django keeping each project in separate virtualenvs makes it easy to work in either version of django furtherit prevents conflicts between system-installed packages and pip installed packages if you try to install the same package using different tools case study to tie it all togetherlet' build simple command-line notebook application this is fairly simple taskso we won' be experimenting with multiple packages we willhoweversee common usage of classesfunctionsmethodsand docstrings let' start with quick analysisnotes are short memos stored in notebook each note should record the day it was written and can have tags added for easy querying it should be possible to modify notes we also need to be able to search for notes all of these things should be done from the command line |
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 attributes for memo itselftagsand creation_date each note will also need unique integer id so that users can select them in menu interface notes could have method to modify note content and another for tagsor we could just let the notebook access those attributes directly to make searching easierwe should put match method on the note object this method will accept string and can tell us if note matches the string without accessing the attributes directly this wayif we want to modify the search parameters (to search tags instead of note contentsfor exampleor to make the search case-insensitive)we only have to do it in one place the notebook object obviously has the list of notes as an attribute it will also need search method that returns list of filtered notes but how do we interact with these objectswe've specified command-line appwhich can mean either that we run the program with different options to add or edit commandsor we have some kind of menu that allows us to pick different things to do to the notebook we should try to design it such that either interface is supported and future interfacessuch as gui toolkit or web-based interfacecould be added in the future as design decisionwe'll implement the menu interface nowbut will keep the command-line options version in mind to ensure we design our notebook class with extensibility in mind if we have two command-line interfaceseach interacting with the notebook objectthen notebook will need some methods for those interfaces to interact with we need to be able to add new noteand modify an existing note by idin addition to the search method we've already discussed the interfaces will also need to be able to list all notesbut they can do that by accessing the notes list attribute directly we may be missing few detailsbut that gives us really good overview of the code we need to write we can summarize all this in simple class diagram |
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 modulesince it will be an executable scriptand we may have other executable scripts accessing the notebook in the future the notebook and note objects can live together in one module these modules can both exist in the same top-level directory without having to put them in package an empty command_option py module can help remind us in the future that we were planning to add new user interfaces parent_directorynotebook py menu py command_option py now let' see some code we start by defining the note class as it seems simplest the following example presents note in its entirety docstrings within the example explain how it all fits together import datetime store the next available id for all new notes last_id class note'''represent note in the notebook match against |
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(selffilter)'''determine if this note matches the filter text return true if it matchesfalse otherwise search is case sensitive and matches both text and tags ''return filter in self memo or filter in self tags before continuingwe should quickly fire up the interactive interpreter and test our code so far test frequently and often because things never work the way you expect them to indeedwhen tested my first version of this examplei found out had forgotten the self argument in the match functionwe'll discuss automated testing in python design patterns for nowit suffices to check few things using the interpreterfrom notebook import note note("hello first" note("hello again" id id match('hello'true match('second'false |
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 notes append(note(memotags)def modify_memo(selfnote_idmemo)'''find the note with the given id and change its memo to the given value ''for note in self notesif note id =note_idnote memo memo break def modify_tags(selfnote_idtags)'''find the note with the given id and change its tags to the given value ''for note in self notesif note id =note_idnote tags tags break def search(selffilter)'''find all notes that match the given filter string ''return [note for note in self notes if note match(filter)we'll clean this up in minute firstlet' test it to make sure it worksfrom notebook import notenotebook notebook( new_note("hello world" new_note("hello again" notes [<notebook note object at xb ac> |
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 both methods are trying to identify the note with given id before doing something to that note solet' add method to locate the note with specific id we'll prefix the method name with an underscore to suggest that the method is for internal use onlybut of courseour menu interface can access the method if it wants todef _find_note(selfnote_id)'''locate the note with the given id ''for note in self notesif note id =note_idreturn note return none def modify_memo(selfnote_idmemo)'''find the note with the given id and change its memo to the given value ''self _find_note(note_idmemo memo this should work for now let' have look at the menu interface the interface simply needs to present menu and allow the user to input choices here' our first tryimport sys |
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 modify note quit """def run(self)'''display the menu and respond to choices ''while trueself display_menu(choice input("enter an option"action self choices get(choiceif actionaction(elseprint("{ is not valid choiceformat(choice)def show_notes(selfnotes=none)if not notesnotes self notebook notes for note in notesprint("{ }{ }\ { }formatnote idnote tagsnote memo)def search_notes(self) |
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 tagsself notebook modify_tags(idtagsdef quit(self)print("thank you for using your notebook today "sys exit( if __name__ ="__main__"menu(run(this code first imports the notebook objects using an absolute import relative imports wouldn' work because we haven' placed our code inside package the menu class' run method repeatedly displays menu and responds to choices by calling functions on the notebook this is done using an idiom that is rather peculiar to pythonit is lightweight version of the command pattern that we will discuss in python design patterns the choices entered by the user are strings in the menu' __init__ methodwe create dictionary that maps strings to functions on the menu object itself thenwhen the user makes choicewe retrieve the object from the dictionary the action variable actually refers to specific methodand is called by appending empty brackets (since none of the methods require parametersto the variable of coursethe user might have entered an inappropriate choiceso we check if the action really exists before calling it each of the various methods request user input and call appropriate methods on the notebook object associated with it for the search implementationwe notice that after we've filtered the noteswe need to show them to the userso we make the show_notes function serve double dutyit accepts an optional notes parameter if it' suppliedit displays only the filtered notesbut if it' notit displays all notes since the notes parameter is optionalshow_notes can still be called with no parameters as an empty menu item |
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 bug can be solved by modifying the notebook class' _find_note method to compare the values using strings instead of the integers stored in the noteas followsdef _find_note(selfnote_id)'''locate the note with the given id ''for note in self notesif str(note id=str(note_id)return note return none we simply convert both the input (note_idand the note' id to strings before comparing them we could also convert the input to an integerbut then we' have trouble if the user had entered the letter "ainstead of the number " the problem with users entering note ids that don' exist can be fixed by changing the two modify methods on the notebook to check whether _find_note returned note or notlike thisdef modify_memo(selfnote_idmemo)'''find the note with the given id and change its memo to the given value ''note self _find_note(note_idif notenote memo memo return true return false this method has been updated to return true or falsedepending on whether note has been found the menu could use this return value to display an error if the user entered an invalid note this code is bit unwieldy thoughit would look bit better if it raised an exception instead we'll cover those in expecting the unexpected |
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 dividing it into few modules or even packages and play with the syntax if you don' have such projecttry starting new one it doesn' have to be something you intend to finishjust stub out some basic design parts you don' need to fully implement everythingoften just print("this method will do something"is all you need to get the overall design in place this is called topdown designin which you work out the different interactions and describe how they should work before actually implementing what they do the conversebottomup designimplements details first and then ties them all together both patterns are useful at different timesbut for understanding object-oriented principlesa top-down workflow is more suitable if you're having trouble coming up with ideastry writing to-do application (hintit would be similar to the design of the notebook applicationbut with extra date management methods it can keep track of things you want to do each dayand allow you to mark them as completed nowtry designing bigger project it doesn' have to actually do anythingbut make sure you experiment with the package and module importing syntax add some functions in various modules and try importing them from other modules and packages use relative and absolute imports see the differenceand try to imagine scenarios where you would want to use each one summary in this we learned how simple it is to create classes and assign properties and methods in python unlike many languagespython differentiates between constructor and an initializer it has relaxed attitude toward access control there are many different levels of scopeincluding packagesmodulesclassesand functions we understood the difference between relative and absolute importsand how to manage third-party packages that don' come with python in the next we'll learn how to share implementation using inheritance |
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 object-oriented designinheritance allows us to create is relationships between two or more classesabstracting common logic into superclasses and managing specific details in the subclass in particularwe'll be covering the python syntax and principles forbasic inheritance inheriting from built-ins multiple inheritance polymorphism and duck typing basic inheritance technicallyevery class we create uses inheritance all python classes are subclasses of the special class named object this class provides very little in terms of data and behaviors (the behaviors it does provide are all double-underscore methods intended for internal use only)but it does allow python to treat all objects in the same way if we don' explicitly inherit from different classour classes will automatically inherit from object howeverwe can openly state that our class derives from object using the following syntaxclass mysubclass(object)pass |
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 in this casethe superclass is objectand mysubclass is the subclass subclass is also said to be derived from its parent class or that the subclass extends the parent as you've probably figured out from the exampleinheritance requires minimal amount of extra syntax over basic class definition simply include the name of the parent class inside parentheses after the class name but before the colon terminating the class definition this is all we have to do to tell python that the new class should be derived from the given superclass how do we apply inheritance in practicethe simplest and most obvious use of inheritance is to add functionality to an existing class let' start with simple contact manager that tracks the name and -mail address of several people the contact class is responsible for maintaining list of all contacts in class variableand for initializing the name and address for an individual contactclass contactall_contacts [def __init__(selfnameemail)self name name self email email contact all_contacts append(selfthis example introduces us to class variables the all_contacts listbecause it is part of the class definitionis shared by all instances of this class this means that there is only one contact all_contacts listwhich we can access as contact all_ contacts less obviouslywe can also access it as self all_contacts on any object instantiated from contact if the field can' be found on the objectthen it will be found on the class and thus refer to the same single list be careful with this syntaxfor if you ever set the variable using self all_contactsyou will actually be creating new instance variable associated only with that object the class variable will still be unchanged and accessible as contact all_contacts |
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 friends insteadlet' create new supplier class that acts like our contact classbut has an additional order methodclass supplier(contact)def order(selforder)print("if this were real system we would send "'{}order to '{}'format(orderself name)nowif we test this class in our trusty interpreterwe see that all contactsincluding suppliersaccept name and -mail address in their __init__but only suppliers have functional order methodc contact("some body""somebody@example net" supplier("sup plier""supplier@example net"print( namec emails names emailsome body somebody@example net sup plier supplier@example net all_contacts [ order(" need pliers"traceback (most recent call last)file ""line in attributeerror'contactobject has no attribute 'orders order(" need pliers"if this were real system we would send ' need pliersorder to 'sup plier sonow our supplier class can do everything contact can do (including adding itself to the list of all_contactsand all the special things it needs to handle as supplier this is the beauty of inheritance |
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 this method actually belongs to the list itself we can do this using inheritanceclass contactlist(list)def search(selfname)'''return all contacts that contain the search value in their name ''matching_contacts [for contact in selfif name in contact namematching_contacts append(contactreturn matching_contacts class contactall_contacts contactlist(def __init__(selfnameemail)self name name self email email self all_contacts append(selfinstead of instantiating normal list as our class variablewe create new contactlist class that extends the built-in list thenwe instantiate this subclass as our all_contacts list we can test the new search functionality 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 'are you wondering how we changed the built-in syntax [into something we can inherit fromcreating an empty list with [is actually shorthand for creating an empty list using list()the two syntaxes behave identically[=list(true |
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 constructed when using the {syntax shorthandclass longnamedict(dict)def longest_key(self)longest none for key in selfif not longest or len(keylen(longest)longest key return longest this is easy to test in the interactive interpreterlongkeys longnamedict(longkeys['hello' longkeys['longest yet' longkeys['hello ''worldlongkeys longest_key('longest yetmost built-in types can be similarly extended commonly extended built-ins are objectlistsetdictfileand str numerical types such as int and float are also occasionally inherited from overriding and super soinheritance is great for adding new behavior to existing classesbut what about changing behaviorour contact class allows only name and an -mail address this may be sufficient for most contactsbut what if we want to add phone number for our close friends |
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 namein the subclass no special syntax is needed to do thisthe subclass' newly created method is automatically called instead of the superclass' method for exampleclass friend(contact)def __init__(selfnameemailphone)self name name self email email self phone phone any method can be overriddennot just __init__ before we go onhoweverwe need to address some problems in this example our contact and friend classes have duplicate code to set up the name and email propertiesthis can make code maintenance complicated as we have to update the code in two or more places more alarminglyour friend class is neglecting to add itself to the all_contacts list we have created on the contact class what we really need is way to execute the original __init__ method on the contact class this is what the super function doesit returns the object as an instance of the parent classallowing us to call the parent method directlyclass friend(contact)def __init__(selfnameemailphone)super(__init__(nameemailself phone phone this example first gets the instance of the parent object using superand calls __init__ on that objectpassing in the expected arguments it then does its own initializationnamelysetting the phone attribute note that the super(syntax does not work in older versions of python like the [and {syntaxes for lists and dictionariesit is shorthand for more complicated construct we'll learn more about this shortly when we discuss multiple inheritancebut know for now that in python you would have to call super(emailcontactself__init__(specifically notice that the first argument is the name of the child classnot the name as the parent class you want to callas some might expect alsoremember the class comes before the object always forget the orderso the new syntax in python has saved me hours of having to look it up |
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 parameters before forwarding them to the superclass multiple inheritance multiple inheritance is touchy subject in principleit' very simplea subclass that inherits from more than one parent class is able to access functionality from both of them in practicethis is less useful than it sounds and many expert programmers recommend against using it as rule of thumbif you think you need multiple inheritanceyou're probably wrongbut if you know you need ityou're probably right the simplest and most useful form of multiple inheritance is called mixin mixin is generally superclass that is not meant to exist on its ownbut is meant to be inherited by some other class to provide extra functionality for examplelet' say we wanted to add functionality to our contact class that allows sending an -mail to self email sending -mail is common task that we might want to use on many other classes sowe can write simple mixin class to do the -mailing for usclass mailsenderdef send_mail(selfmessage)print("sending mail to self emailadd -mail logic here for brevitywe won' include the actual -mail logic hereif you're interested in studying how it' donesee the smtplib module in the python standard library this class doesn' do anything special (in factit can barely function as standalone class)but it does allow us to define new class that describes both contact and mailsenderusing multiple inheritanceclass emailablecontact(contactmailsender)pass the syntax for multiple inheritance looks like parameter list in the class definition instead of including one base class inside the parentheseswe include two (or more)separated by comma we can test this new hybrid to see the mixin at worke emailablecontact("john smith""jsmith@example net" |
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 warnings about multiple inheritance are we'll get into the complexities in minutebut let' consider some other options we hadrather than using mixin herewe could have used single inheritance and added the send_mail function to the subclass the disadvantage here is that the -mail functionality then has to be duplicated for any other classes that need -mail we can create standalone python function for sending an -mailand just call that function with the correct -mail address supplied as parameter when the -mail needs to be sent we could have explored few ways of using composition instead of inheritance for exampleemailablecontact could have mailsender object instead of inheriting from it we could monkey-patch (we'll briefly cover monkey-patching in python object-oriented shortcutsthe contact class to have send_mail method after the class has been created this is done by defining function that accepts the self argumentand setting it as an attribute on an existing class multiple inheritance works all right when mixing methods from different classesbut it gets very messy when we have to call methods on the superclass there are multiple superclasses how do we know which one to callhow do we know what order to call them inlet' explore these questions by adding home address to our friend class there are few approaches we might take an address is collection of strings representing the streetcitycountryand other related details of the contact we could pass each of these strings as parameter into the friend class' __init__ method we could also store these strings in tuple or dictionary and pass them into __init__ as single argument this is probably the best course of action if there are no methods that need to be added to the address |
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 statically this is an example of compositionas we discussed in object-oriented design the "has arelationship of composition is perfectly viable solution to this problem and allows us to reuse address classes in other entities such as buildingsbusinessesor organizations howeverinheritance is also viable solutionand that' what we want to explore let' add new class that holds an address we'll call this new class "addressholderinstead of "addressbecause inheritance defines an is relationship it is not correct to say "friendis an "addressbut since friend can have an "addresswe can argue that "friendis an "addressholderlaterwe could create other entities (companiesbuildingsthat also hold addresses here' our addressholder classclass addressholderdef __init__(selfstreetcitystatecode)self street street self city city self state state self code code very simplewe just take all the data and toss it into instance variables upon initialization the diamond problem we can use multiple inheritance to add this new class as parent of our existing friend class the tricky part is that we now have two parent __init__ methods both of which need to be initialized and they need to be initialized with different arguments how do we do thiswellwe could start with naive approachclass friend(contactaddressholder)def __init__selfnameemailphone,streetcitystatecode)contact __init__(selfnameemailaddressholder __init__(selfstreetcitystatecodeself phone phone |
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 call the initializer that wouldn' break this examplebut it could cause hard-to-debug program crashes in common scenarios imagine trying to insert data into database that has not been connected tofor example secondand more sinisteris the possibility of superclass being called multiple times because of the organization of the class hierarchy look at this inheritance diagramobject +_init_(contact addressholder +_init_(+_init_ friend +_init_(the __init__ method from the friend class first calls __init__ on contactwhich implicitly initializes the object superclass (rememberall classes derive from objectfriend then calls __init__ on addressholderwhich implicitly initializes the object superclass again this means the parent class has been set up twice with the object classthat' relatively harmlessbut in some situationsit could spell disaster imagine trying to connect to database twice for every requestthe base class should only be called once onceyesbut whendo we call friendthen contactthen objectthen addressholderor friendthen contactthen addressholderthen objectthe order in which methods can be called can be adapted on the fly by modifying the __mro__ (method resolution orderattribute on the class this is beyond the scope of this book if you think you need to understand iti recommend expert python programmingtarek ziadepackt publishingor read the original documentation on the topic at |
Subsets and Splits