0% found this document useful (0 votes)
39 views15 pages

Object POOP

oop

Uploaded by

galo gali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
39 views15 pages

Object POOP

oop

Uploaded by

galo gali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 15
Object-Oriented Programming (OOP) i by David Amos #103 Comments ‘> (ammein] Mark as Completed GI Table of Contents + Whatis Object-oviented Programming in Python? + Define aClass in Python © Classes s Instances © HowtoDefinea class * instantiate an Object in Python, © Class and Instance Ateebutes © Instance Methods © Check Your Understanding * Inherit From Other Classesin Python © DogPark Example © Parent Classes vs Child Classes © fend the Functionality of Parent © Check Your Undesanding + concusion aster Rea ord Python kl "With Communiy of Experts ' Level Up With Unlimited Access to Our Vast Library cc cy ct Python Tals and eo Lessons © temo ads (CETTE Thistutoriathas a related video course create by the Real Python team. Watch it together withthe written tutorial to deepen your understanding: Intro to Object-Oriented Programming (OOP) in Python Object-oriented programming (00?) isa method of structuring a program by bundling related properties and behaviors into individual objects. nts tutorial you'l learn the basics of object-oriented programming in Python. Conceptually object are lke the components ofa system. Think ofa program as factory assembly ine of ors. At leach step ofthe assembly line a system component processes some material ultimately transforming aw material into a finished product. ‘An object contains data ke the raw or preprocessed materials at each step on an assembly line, and behavior, ke ‘the action each assembly line component performs. In this tutorial, you'll learn how to: + Create a class, which s ikea blueprint for creating an object + Use classes to create new objects + Model systems with elass inheritance Note: This tutorials adapted from the chapter “Object-Oriented Programming (00P}" in thon Bases: Practical introduction to Pythan 3. ‘The book uses Python's built-in DLE editor to create and et Python files anc interact withthe Python shell, so you willsee occasional references to IDLE throughout this tutorial However, you should have no problems running the example code frm the editor and environment of your choice. Free Bonus: Click here to get access to a free Python OOP Cheat Sheet that points you tothe best tutorials, videos, and books to learn more about Object-Oriented Programming with Python, What Is Object-Oriented Programming in Python? Object-oriented programming sa programming paradigm th properties and behaviors are bundled into individual objects. rovides a means of structuring programsso that Forinstance, an abject could represent a person with properties like 3 name, age, and address and behaviors such as walking, talking, breathing, an¢ running. Ort could represent an email with properties lke recipient is, subject, and body and behaviors lke adding attachments and sending. Put another way, object-oriented programmingis an approach for modeling concrete, real-world things ike cars 3s well as relations between things, ike companies and employees, students and teachers, and so on, OOP models real- ‘world entities a software object that have some data associated with them and can perform certain functions ‘Another common programming paradigm is procedural programming, which structures a program lke 2 recipe in thatit provides a set of steps, in the form of functions ane code blocks, that low sequentially in order to complete a task The hey takeaways that objects ae at the center of object-oriented proprammingin Python, not only representing the data, asin procedural programming, butin the overall structure of the program as well aT y Become a Python Expert » ri Become a Python Expert © nemoveads Define a Class in Python Primitive data structures—tke numbers, stengs, and lsts—are designed to represent simple pieces of information, such asthe cost ofan apple, the name ofa poem, or your favorite colors espectively, What if you want to represent something more complex? For example le’ say you want to track emplayees in an organization. You need to store some basic information about each employee, such as their name, age, postion, and the year they started working Cone way todo this isto represe zach employee a list: Python kick = (-3anes Kick", 36, “Captain®, 2268) Spock = {"5pock", 35, *SCtence ovticer", 2254) iceoy = [Leonard Mecoy", “oniet medical OFFcen, 2266] ‘There area numberof issues with this approach, First, itcan make larger code files more dificult to manage. you relerence kirk] several lines aay from where the kirk lists declare, willyou remember thatthe element with index isthe employee's name? ‘Second, itcan introduce erorsif not every employee has the same number of elements inthe list Inthe wecoy ist above, the age is missing, so-ecoyi1] will return “chiet Wectcal of¢scer" insteag of Dr. McCoy's age, ‘Agreat way to make this type of code more manageable and more maintainable sto use classes. Classes vs Instances lasses are used to create user-defined data structures Classes define functions called methods, which identify the behaviors and actions that an object created from the class can perform with ts data In this tutorial, you'l create a bog class that stores some information about the characteristics and behaviors that an Individual dog can have, ‘class isa blueprint for how something should be defined. It doesn’t actually contain any data, The bog class specifies ‘that name and an age are necessary for defining a dog, but it doesn't contain the name or age of any speci do. While the lasss the blueprint, an instance isan object that's bull fom a class and contain real data. An instance of theoog clas is nota blueprint anymore t's an actual dog witha name, ike Miles, who's four years ol Put another way, aclassisike a form or questionnaire. An instances ke a form that hasbeen filed out with information. Jus like many people can fil out the same form with their own unigue information, many instances can be created from asingle clas. How to Define a Class Allclas definitions start with the ciass keyword, which i followed by the name ofthe class and a colon. Any code thats indented below the class definition is considered part of the class's body. Here's an example ofa og clas: Python cass bo ‘The body of the Dog lass consists ofa single statement the pass keyword. pass ls often used asa placeholder Indicating where code will eventually go. I allows you to run tis code without Python throwing an error Note: Python class names ae written in Capitalizedords notation by convention. For example, acass fora specific breed of dog tke the Jack Russell Terrier would be written as JackRusseliTesrter. The og clas ist very interesting right now, so let's spruce itup abit by defining some properties thatalloog objects should have, There ave a numberof properties that we can choose from, including name, ag, coat color, and breed, To keep things simple, welljust use name and age. ‘The properties that all og objects must have are defined in a method called ._ init_(). Everytime a newbvg abject Iscreated, _intt__( sets the initial state ofthe object by assigning the values of the objects properties. Thats, sntt_()ntializes each new instance of the clas. YYoucan give ._init_() any numberof parameters, but the fst parameter wil always be a variable called self When a new cass instance is create, the instance fs automaticaly passe tothe self parameterin .__init_( $0 ‘that new attributes can be defined on the object. Lets update thecog class with an .__ants__() method that ee 5 crane and, age attributes: Python class bo: def —inkt_(selt, name, age) Notice thatthe ._snst_() method's signatuteisindented four spaces. The body ofthe methods indented by eight spaces, This indentation is vitally important, IttllsPython thatthe ._init_() method belongs to the oor class, In the body of ._snst_(), there are two statements using the seit variable: 1. seif.nane = none creates an atribute called nane and assigns tet the value ofthe mare parameter. 2.setf.age = age creates an attribute called age and assigns to tthe value ofthe age parameter. ‘Atributescreatedin _intt_() are called instance attributes. An instance atuibute's values specific to a particular Instance ofthe class. Alloog objects have a name and an age, b depending onthe noe instance. thevaluesfor the nane and age attributes wll ary On the other hand, elass attributes are attributes tha have the same value forall class instances. You can define a class attribute by assigning a value toa variable name outside of ._snst_() For example the following bog class has a clas attribute called specter withthe value "canis fontTSaris" Python class bo ot anse_teelsy mane, age Class attributes are defined directly beneath thefrstline ofthe class name and ae indented by four spaces. They ‘must always be assigned an iia value, When an instance of the lassis created, class attribute are automatically created and assigned to their intial values. Use cass attributes to define properties that should have the same value fr every class instance. Use instance attributes for properties that vary from one instance to another Now that we have abo class et’ create some dogs! Learn Python » © Remove ds Instantiate an Object in Python OpenioLe's ractve window and type efollowing Python This creates a new o0g clas with no attributes or methods. Creatinga new object from a cassis called insta ing an object. You can instantiate anew bog abject by typing the name of the clas, followed by opening and closing parentheses Python ~ > 0080) <_ssin_oog obsect st 611057626300 ‘You now have anew dog object at 1105702630. This funny-looking string ofletters and numbers sa memory address that indicates where the dog objects storedin your computer's memory. Note thatthe address you see on your screen willbe different. Now instantiate a secondove abject: Python ~ > b0e0) <_ssin__.0og object at exBee4ccc86> The new coginstance is located ata different memory address. That's because i's an entirely new instance ands completely unique from thefrstoog object that you instantiate, ‘Tosee this another way, type the following: Python ~ oo a= beet) ae) In this code, you create two new bog objects and assign them tothe variables a and When you compares and Using the = operator, the result is Fae. Even though «and bare both instances ofthe Gog class, they represent two distinc objects in memory Class and Instance Attributes Now create new bog class witha class attribute called. spectes and two instance atibutes called rave and .age: Python ~ o> class bo: oe 1 mee) init am To instantiate objects of thisoog class, you need to provide values fr the nane and age. Ifyou don’, then Python raises atypeterar: Python oe 99 0060) Traceback (nost recent call Tost) File "epystell#=>", Tine 2, tn enogute> ogt) Typeeeron: _intt_() nissing 2 required positional argunents: To pass arguments tothe nane and age parameters, put values into the parentheses ater the class name: Python a p> busy = bogt"Buey", 8) Dep alles = bog(*hiles", 4) This creates two new bog nstances—one for nine-year-old dog named Buddy and one fora four-year-old dognamed Miles. Theog class's ._sntt__() method has three parameters, so why are only two arguments passed toi nthe example? ‘When you instantiate og object, Python creates anew instance and passes itto the fist parameter of This essentaly removes the sei¢ parameter, so you only need to worry about the nane and age parameters anss_0. ‘After you create the Dog instances, you can access their instance attributes using dot notation: Python ve >> tut. mane ued o> ables. age You can access class atributes the same way! Python - >> busy species Cone of the biggest advantages af using classes to organize datas thatinstances are guaranteed to have the attributes ‘you expect. All bog instances have species, .nane, and .ageatibutes, so you can use those attributes with confidence knowing that they will always return a value Although the atuibutes are guaranteed to ens, their values con be changed dynamical Python _ 259 miles-specios = “Felis silvestris! “Felis silvesteis In this example, you change the -ag attribute of the busy object to 10. Then you change the species attribute of the lies objectto “Felis stivestris", whichisa species of cat. That makes Miles a pretty strange dog, but itis valid Python! “The key takeaway heres that custom objects are mutable by default, An objectis mutable fitcan beatered dynamically. For example, its and sare mutable, but strings and tuples are immutable. © Remove ads Instance Methods Instance methods are functions that are defined inside a class and can only be called from an instanceof that class. Justlike ._ init_(),aninstance method's frst parameter is always self (open a new editor window in IDLE and type inthe following og class Python class bog species = “Conte fantlsarss® det Linkt_(selt, name, age) Get desersption(sei(): return #"(50)f rane) #5 (50if.age) yours ole” { roorner snstance method et speak(oelt, sone): return #7 (oelfonane} says {sound “This bog class has two instance methods 1. sdeseription() returns a string displaying the name and age ofthe dog. 2, .speak() has one parameter called soune and returns string containing the dog's name ané the sound the dog mates. Save the modified nog clas oa file called 4og-py and press F Ito run the program. Then open the interactive window and type the following to see your instance methods in actlon: Python ~ Dep alles = bog("nLIes", 4) o> ates doscristion() ‘wales 1s 4 years ole 99 miles speak("WEOF Hooe") 55 miles. speak("Bow Hou") Inthe above bog clas, description() retumsa string containing information about the dog instance niles. When. ‘writing your own classes, i's a good idea ta have a method that returns a string containing useful information sbout aninstance of the class However, .deserfption() int the most Pythonic way of doing ths. ‘When you create a List object, you can use print to dsplaya string that looks lke thelist: Python - de> names = ['Fleteher", "bovis", *ban*] 255 prunténanes) [tetener", "Davie", oan") Lets see what happens when you print() the ales objec: Python > o> seintgettes) {leain__Oop object a€ oyb030¢¢705 ‘When you print(aiies), you get a cryptic looking message telling you that niles aoog object atthe memory address oxeenet*70. This message srt very helpful. You can change what gets printed by defining a special instance: method called ._str_0. In the editor window, change the name of the og class's .description() methodto ._st-_(): Python class bog 1 Leave other parts of Dog class as-is W heplace -eeseription() with ste) def _ste_(seis) Feturs #(salfsnana} Ss (seDf-age) years ots? Save the fil and press| FS | Now, when you print(niles), you get a much friendlier output Python a o> miles = Dogtniles”s 4) os poant(nsles) Iilee Ae & years ole Methods tke ._init_() and ._str_() are called dunder methods because they begin and end with double Underscores. There ae many dunder methods that you can use to customize classes in Python. Athough too advanced a topic for a beginning Python book, understanding dunder methods san important par of mastering objectoriented programmingin Python, In the next section, you'l se how to take your knowledge one step further and create classes from other classes, 0 semoveads Check Your Understanding Expand te blockbelow to check your understanding tvercise: Create a Car Class showitide ‘You can expand the blockbelow to see a solution: Solution: Create Car Class ShowiHide |When you're ready, you can mave on tothe nest section. Inherit From Other Classes in Python Inheritance the process by which one cass takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that child classes are derived from are called parent classes. Not Practical introduction to Python 3. you enjoy what you're reading, then be sure to check ou book and he learning path, is tutrialis adapted from the chapter “Object Oriented Programming {OOF} n Python Basics: the rest ofthe ‘You can also check out the Python Basics: Building Systems With Classes video course to reinforce the skills that you'l develop inthis section ofthe tutorial Chit classes can override or extend the attributes and methods of parent clases, In other words, child classes inherit allof the parent's attributes and methods but can also specity attributes and methods that are unique to themselves, Although the analogy isnt perfect, you can think of object inheritance sort of like genetic inheritance. ‘You may have inherited your hair color from your mother. 'san attribute you were born with. Let's say you decide to ‘olor your hair purple. Assuming your mather doesn’ have purple halr, you've just overridden the hair color attribute ‘that you inherited from your mom, You also inherit ina sense, your language from your parents. If your parents speak English, then you'll also speak English Now imagine you decide to learn a second language, ike German. inthis case you've extended your artributes because you ve added an ateibute that your parents don't have. Dog Park Example Pretend for a moment thatyou'e ata dog park. There are many dogs of cfferent breeds atthe park, all engaging in various dog behaviors. Suppose now that you want to model the dog park with Python clases. The oog class that you wrote inthe previous section can distinguish dogs by name and age but not by bree. ‘You could modify the bog clas inthe editor window by adding a bree attribute Python class bog species = “Canis fantliarss* def _init_(selt, rane, age, breed): The instance metnods defined earier are omitted here because they aren't important for this discussion. Press| F5_tosave theflle Now you can model the dog park by instantiting abunch of ifferent dogs inthe Interactive window: Python ~ o> miles « bog(chites", 4, “Jack Musseld Terrder*) 29> muddy = Dogt“sudey", 9, “Dacrsnurd”) 595 gaee = Bog("250e", 3, “butldop") 95 Hm = bog("218", §, “autte68") ach breed of dog has slightly diferent behaviors. For example, bulldogs have low bark that sounds like woof, but busy speak("¥59") 29> gam. speak("m00°) Dia cays hoot >> Jace spene("wo0#) Passing string to every callto -speak() i repetitive and inconvenient, Moreover, the string representing the sound ‘that eachoog instance makes should be determined by is -breed attribute, but here you have to manualy pass the correct tring to -speak() every time its called, You can simplify the experience of working withthe dog class by creating 2 child class for each breed of dog, This allows youto extend the functionality that each child class inherits, including specifying a default argument for speak). “1 wished | had access to a book like this when | “orc amin yon monotone" — Mariatta Wijaya, CPython Core Developer Parent Classes vs Child Classes Lets crete a child class fr each ofthe three breeds mentioned above: Jack Russell Terrier, Dachshund, and Bulldog, For reference, here's the fll definition of the og class Python clses bo et Lanse teelty name, age selfoage © age def _ate_(ei Feeurs f{selfsnae} £5 (senf.age) years ots” ot apeak(oolt soar) seeura ¢°(eahf-mane) says (round) Remember, to create a chil lass, you create new class with ts own name and then put the name ofthe parent class in parentheses. Ad the following tothe dog. py file to create three new child classes ofthe oog cass: Python clase 2ucktuseel Tereter (00g) ‘lave bachshund(0g) class Bulldog(008) Press| F5_ to save and un the file. With the child classes defined, you can now instantiate some dogs of specific breeds in the interactive window: Python > doy alles - aackRunselTterrier(*hites", 4) 29> mua = Dachshund bude", 9) 99 Jack » Buldeog("23ck", 3) 99 33m = aullepgt 250", 5) Instances of child lasses inherit all ofthe attributes and methods ofthe parent class Python ~ >> busy. name >> pranttsaek) 29> sm. speak(“Mioe") To determine which class agen object belongs to, you can use the bultn ype Python ~ >> sypetmttes) ‘elses '_orstn__JeekRussellTeresen'> ‘Whatif you want to determine faites is also an instance ofthe dag class? You can do this with the builtin Asinstance(y: Python oe > isinatancetele 0g) Notice that tsinetance() takes two arguments, an object anda class. Inthe example above, sstnstance() checks if silos isan instance ofthe bog class and returns true Theres, busy, jack, and jin objects are all Og instances, Buttes Is nota auhLdog instance, and jack is nota bachshund instance: Python 2 tstnstancefettes, 11608) >> Asinstance(Sack, oachshund) False More generally all objects created from a child class a instances of the parent class although they may not be instances of other hil classes, Now that you've created child classes for some diferent breeds of dogs, let's gve each breed its own sound. Extend the Functionality of a Parent Class Since diferent breeds of dagshave slightly different barks, you want to provide a default value forthe sound argument of their respective .speak() methods. To do ths, ou need to override speak) in the class definition for each breed, ‘To override a method defined on the parent class you define a method with the same name on the child class Here's what hat looks like forthe 2ackussell Terrier class Python class Sackausseltereter(008) et epeakleel’, soana="A00) feturn #(Seitvrane} 5095 {sound} Now speak) is defined on the 2actussel1 Terrier class with the default argument fr sound set to “Are. ‘Update dog.py with the new aackRusseli Terrier class and press FS. to save and run thefile, You can now call spesk() 002 JackRussel Terrier instance without passing an argument to sound Python ~ o> niles = JackRussellTerrder(niles", 4) o> miles. speak) eles says are Sometimes dogs make diferent barks, soi Miles gets angry and growls, you can stil call .speak¢) witha different sound Python a o> alles. speak("ore=") “wales say roe" Cone thing to keepin ming about cass inheritance is that changes to the parent class automatically propagate to child classes. Ths occurs as long asthe attribute or methed being changed isn: overridden inthe child class. For example inthe editor window, change the string returned by .speak() inthe dug class: Python class bo 1 Leave other attributes and ssthads a= they are 1 change the string returned ty .speak() et speak(selt, sound): eeturn #{seitsnane} barks: {sound} Save thefile and press|F5 | Now, when you create 3 new Bulteog instance named jim, jin-sp string: Python oe 95 $3m = autteng("386", 5) o> Fim. speak("207") However, calling speak() on a Jacktussel Terrier instance won't show the new style of output Python >» o> alles = DackRusselTTerrier(*Hi2es", 4) o> miles. speak) Sometimes it makes sense to completely override a method from a parent clas. Buti this instance, we don’s want ‘the JackRussel Terrier class to lose any changes that might be made tothe formating ofthe output string of bog speak) Todo this, you still need to define a .speak() method onthe child ecktussel1Terrser class, Butinstead of explicitly efining the output sing, you need to cal the og class's speak) inside ofthe child class's. speak) using the same. arguments that you passed to acknuscellterrser. speak() ‘You can access the parent class from inside a method of achilé classy using uae): Python class 3ackRusselTereter(008) 49 speak(sel¢, sound>"A0#) return super). speak(souné) ‘When you call super().speak{soune) inside sackausseliterrder Python Searches the parent class, og, fora =pe3k0) ‘method and calls itwith the variable sour. Update dog.sy with the new aackRusseltTerrier class Save the ile and press FS. so,you can testi inthe interactive window Python oe de> alles = dackRunselTTerrier(*hiles", 4) sos males speak) sles bares: Are Now when you call nites. speak), you'll see output reflecting the new formatting in the og class, Note: Inthe above examples, the lass hlerarchy is very staightorward, The acktussellTerrter classhasa single parent class, og In real-world examples, the class hierarchy can get quite complicated. super() does much more than just search the parent cass fora method or an attribute. It traverses the entre class hierarchy fora matching method or attribute. I you aren't careful, super) can have surprising results, “1don’t even feel like I've scratched the ty surface of what I can do with Python” id © femaveads Check Your Understanding Expand the block below te check your understanding: Exercise: lass Inheritance Show/Hide You can expand the block below to see a solution: Solution: Class Inheritance Show/tiide Conclusion In this eutoral, ou leamed about object-oriented programming (O0P] in Python, Most modern programming languages, such as Java, Cand C+, follow 00? principles, so the knowledge you gained here willbe applicable no matter where your programming careertakes you. In this tutorial, you learned how to: + Define class, which isa sort of blueprint for an object * Instant an objectfromaciass + Use attributes and methods to define the properties and behaviors ofan object + Useinheritance to create ehild classes rom a parent class + Reference a method on a parent class using super() *+ Check fan object inherits from another class using Asinetance() you enjoyed what you leatned i to checkout theres ofthe book. is sample from Python Basics: 4 Practical introduction to Python 2, then be sure Markascompleted oO @ (TTT This tutorial has a related video cours ated by the Real Python team. Watch itzogether with the written tutorial to deepen your understanding: Intro to Object-Oriented Programming (OOP) in Python @ Python Tricks @ Geta short & sweet Python Trick delivered to your inbox every couple of ays. No spam ever. Unsubscribe any time, Curated by the Real Python Email Address About David Amos David sa writer, programmer, and mathematician passionate about exploring mathematics ‘through code More about David Each tutorial at Real Python is creted bya team of developers so that it meets our high quality stondards. The team members who worked on this tutorial are ® © & Master Real-World Python Skills With Unlimited Access to Real Python inus and got access to thousands of tutorials, hands-on video courses, and a community of expert Pythonista Licsurronrnsits | What Do You Think? Ratethisartice:

You might also like