160 likes | 373 Views
Chapter 19, 20 Object Oriented Programming (OOP). Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012. What is OOP. To qualify as being truly object-oriented objects generally need to also participate in something called an inheritance hierarchy
E N D
Chapter 19, 20 Object Oriented Programming (OOP) Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012
What is OOP • To qualify as being truly object-oriented objects generally need to also participate in something called an inheritance hierarchy • Inheritance --- a mechanism of code customization and reuse, above and beyond anything we’ve seen so far
Class tree • Two key words need to define: 1. Classes Serve as instance factory 2. Instances Represent the product generate from classes
Class tree • We usually call class higher in the tree (like c2 and c3) superclasses; classes lower in the tree (like c1) are known as subclasses • The search procedure (try to look up some specific function belongs to which class) proceeds bottom-up, starting from left to right
Class tree • Suppose we build up the tree • If we say: I2.w It indicates we have an instance2 and it calls the function w • now, we need to search where does the function w defined • Therefore, the Python will search the linked objects in the order: I2, C1, C2, C3 and stop at the first .w it finds • In OOP, I2 “inherits” w from C3
Class tree • I1.x and I2.x both find x in C1 and stop, since C1 is lower than C2 • I1.y and I2.y both find y in C1, since that’s the only y • I1.z and I2.z both find z in C2, since C2 is more to the left than C3 • I2.name finds name in I2, without climbing the tree at all
Class vs. Modules • All of the class and instance objects we put in these trees are just package of names. • If that sounds like modules, it should; • The only difference here is that objects in class tree also have “automatically-search” links to other namespace objects.
Coding the Class Tree • Each “class” statement generates a new class object • Each time a class is called, it generates a new “instance” object • Instances are automatically linked to the class they are created from • Classes are linked to their superclasses
Coding the Class Tree • To build the class tree we just saw, we would run Python code in this form: class C2: … class C3: … class C1 (C2,C3): … I1=C1() I2=C2()
Class Practice • Write a class code to construct a class tree looks like: