0% found this document useful (0 votes)
34 views

Chap 8

Uploaded by

aryanverma20372
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)
34 views

Chap 8

Uploaded by

aryanverma20372
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/ 28
CLASSES AND OBJEctTs 8.1 OVERVIEW OF OOP (OBJECT-ORIENTED PROGRAMMING) As we know, Python is an object-oriented programming (OOP) language and pi required to support object-oriented programming. OOP mainly focuses on the ob procedural programming focuses on the functions and methods. QOP is based on the implementation of real world objects in programming. Such a c Contains objects that contain the data in the form of attributes and classes that ¢ ‘approach, a problem is considered in terms of objects that can be involved in finding the problem instead of procedures. Hence, through this approach, a person can relate a prot ‘objects and can work towards its solution with relative ease. ‘Object is an instance ofa class. A class is a collection of data (variables) and methods isthe basic structure of an object and is a set of attributes, which can be data members Het us understand the concept with an example. We can relate class to a sketch ‘That sketch contains all the information about the structure of the building, suc! fooms. etc. Now, according to our example, the building is an object WH one Model, 30 100 can a class have many objects associated with it Some important terms in OOP are as follows: © Class; Classes are defined by the user; the cl: of data members and method members that © Data Member: A variable defined in either has floors, Just as various bu jass provides the basic structure fo are used by the instances (objects) @ class or an object; it holds the data assoc elass or object, * Instance Variable: A variable that is defined in a method; its seope is only w defines it, © Class Variable: A variable that is defined in the cl @ Instance: An object is an instance of the class. _# Instantiation: The process of creation of an object of ¢ Method: Methods are the functions that are defined instances of the class. © Function Overloading: A function defined more than one tine with ditle function overloading, The operations performed by these lass and can be used by all the ins’ a class. in the definition of class and are erent behaviours isk functions are different Classes and Objects 213 {nheritance: A class ‘A’ that ca , ue. a class inherited from mee ; : Oc teristics of another class ‘B’ is said to be a derived ‘ess is called inheritance, Encapsulation ictions can be imposed on the z Hansa access ; cidental modification in the data ie methods and variables. Such restrictions can be used OOP ‘€ known as Encapsulation. Encapsulation is an important ‘we can say that OOP relies strict! ly on Data Et rus are already familiar with the erm absweens ction can be used as synonyms since both lly, in the context of programming, action. Abstraction means data-hiding, Encapsulation of them relate to the data-hiding concept. Be orients cannot we can restrict the access to some of the object’s components, e accessed from outside the object but from inside the object only. ensuring 2 For accessing these types of data, some special methods are used, ‘These methods are known as getters () and setters (). 442. Polymorphism ~The word ‘Poly’ means “many”. Therefore, the term ‘polymorphism’ means that the object of a class can have many different forms to respond in different ways to any message or action. Jnother words, polymorphism is the capability for a message or data to be processed in one or more ways- Let us look at an example: ~ Ifa base class is mammals, then horse, human, and cat are its subclasses. All the mammals can see in the ‘daytime. Therefore, if the message ‘see in the daytime” passed to mammals, all the mammals including the ‘human, the horse and the cat will respond to it. Whereas, if the message ‘see during the night time! is passed "tothe mammals, then only the cat will respond to the message as it can see during the night as well as in the - taylime, Hence, the cat, which is a mammal, can behave differently from the other mammals. “This is called polymorphism and is illustrated in Fig. 8.1. Class Shape Draw() LS ass Cirle | Class Square (Class Triangle Class Circle lass Sq /Draw() Draw() Draw() Figure 8.1 Polymorphism ly defined structure from which objects are made. It can i vious! m which ob of a previous tt attributes and relationships with each other. share simil: 244 Introduction to Computing & Problem Solving using Python For example: . : © Fruit is a class, and apple, mango and banana are its objects. The attributes of these Objects can color, taste, etc. oe ‘a * Vehicle is a class and car, scooter, bus, truck, etc., can be its objects. The attributes of thes can be speed, brake, power of engine, etc. In Python, a class is defined by using a keyword class. After that, the first statement can be 4 docsty; (optional) that contains the information about he class. Now, inthe body of clas, the tebutes are yon These attributes can be data members or method members. d In Python, as soon as we define a class, the interpreter instantly creates an object that has the Same nam, as the class name. Although, we can create more objects of the same class. With the help of objest. 4" access the attributes defined in the class. © Objess Anew local new space is created by a Class, where all its attributes (data or function) are defined. attributes with double underscores (_)are also present, for example-_doc_gives the docstring ‘as the class is defined, a new class object is created with same name, which allows acces: 1 attributes, also to instantiate new object of that class. ich, year) : ident detail object is created”) (self): *, self.name) + *,self,branch) ple, we have created a class Student that contains two methods: £111 i 1s. The first method £111 details takes four arguments; self, name, > ‘method print details takes exactly one argument; seit, section, we will find out how these class and methods are used, hand same way as the functions are defi! the every method will have self 0s Bema Classes and Objects 215 1, What is Object-Oriented Programming? ‘Ans. The Object-Oriented programming approach m procedural programming focuses on the fied ony ed ame Ce ee Sst ia an i t The object is an instance ofcclass. It isa collection of data (variables) and methods (functions). data members and method members. 2. Define class, method, instance and i i ‘Ans. Class: Classes are defined by the ae See i ieee y user; the class provides the basic structure for an object. It consist mbers and method members that are used by the instances (objects) of the Method: Methods are the functions defined in the definition of class and are used by various instances of the class. Instance: An object is an instance of the class. Function Overloading: A function that can be defined more than one time with different behaviours is known as function overloading. The operations performed by these functions are different. 3. Give the syntax for class definition. class class_nam “This is docstring which is optional’ class_suite ‘is an instance of a class that has some attribut which it is an object. ; be used to access the attribute es and behaviour, The object behaves according to .s of the class. The syntax of creating an object in Python is 246 Introduction to Computing & Problem Solving using Python s Student which we defined earlier. The above statement creates an object s1 of the class ; : Now, we can access the methods (attributes) which are defined in the class s tudent. We can use a fo from the class Student with the object name followed by a dot, which is then followed by the..." name with valid arguments. ¢ can object of Student class = Student () ng another object of Student class dent () od fill details with proper attributes {ls(‘John’,"CSE’,’ 2002’) il object is created iis (“Jack’ ,’ ECE’ ,’2004’) tail object is created ‘print_detail method with proper attributes # Output # Output # Output In this example, we create two objects (instances) s1 and s2 of class Student. Then afterwards, \ the £111 details method of class with the obj oi Lt ith the object names as prefix and passed the valid arg "details ofthe students are stored inthe objects, Now, te second method print_deta ‘Same convention. The method print_details prints the details of all stored students. 8.3.1 Objects are Mutable oe) "Objects are mutable— this statement tells us tha the state ‘making changes to its attributes. ile, consider the class Student which was defined earlier. We c filled : . _ ; We created an object s1 and fille of the student using £411 details method. If, at any point of time, it is required to change the from ECE 10 CSE, it can be done in the same object by reassigning it a new value jed with the of an object can be changed at any point of ime Classes and Objects 247 instan Decenety not O88 student details in that object #41 details (*Jonn’,*EcE*, 2004) PES SAYI chject is created ng details of the Joe yb: wprint_details() ae what if it is required to change the value of br Definitely not. We can change the value in the same ol of object 51 to CS? Will we create a new bject by simply reassigning the value to it. mge the value of branch from ECE fd. fill_details(*John’,’csz’,2004) tudent detail object is n be passed as an argument to a function and a function can also return 218 Introduction to Computing & Problem Solving using Python 2. What do you understand by “Objects are mutable”? Ans. Objects are mutable means that the state of an object can be changed at any point in time by making changes to its attributes. 8.4 OBJECTS AS ARGUMENTS ‘instance of a class can be passed as an argument to a function in Python. Let us say, we have a class Triangle. We make an instance of this class and define the attributes th: __ sides of this triangle. Then, that object or instance of Triangle can be passed to a function which calcu! the perimeter of the triangle. >>>tl = Triangle() pe>tl.a = 10 >>ti.b = 18 >>tl.c = 23° ‘Now, we define a function pez imeter, which calculates the perimeter of a triangle, This function ks ec lox itanioe ofa clas a on argument, per = ti.atti.b+ tl.c _ print (“Perimeter of triangle: “, per) j c __ Now, we pass the object ¢1 to the function Jasses and Objects 219 js in this object. Perimetey that is in this object. "Ses, which calculates the perimeter ofthe triangle >>>perimeter (t1) perimeter of triangle; 51 # Pac a8 argument g.5 OBJECTS AS RETURN VALUES instances of a class can as of ; also be Teturned by a function, i.¢., a function can ret Let us say, we te an object of tr jan, class and a function tp z le. Now, wl i qT; tis f size of the triangl en the object of rr ‘ale class is passed to this function, of the triangle in that object and returns the Double sized triangle that is in the form of ol Mn instances or objects. Jouble that doubles the it doubles the size bject. thods: one is create_triangle, which will create which will print the sides of the triangle. and the other is print_sides, } Triangle: c ite_triangle(self,a,b,c): self.a=a self.b = b Self.c=c Print (“The triangle is created”) sides (self): print (‘Side oe dele va) print (‘Side 7, self.b) Print (‘’Side c: ‘, self.c) “£1 of the Triangle class and create a triangle in it. le (10,20,30) # Output # Returning object # Passing object as argument es the triangle that was passed as an argument, 220 Introduction to Computing & Problem Solving using Python Note The purpose of the dot notation = Sao is to identify the variable you are referring RR EE ONE I 8.6 BUILT-IN CLASS ATTRIBUTES In Python, every class contains various built-in attributes. They can be accessed with a dot operator jysy , in the case of user-defined attributes we have come across earlier. The built-in class attributes in Python are as follows: 1. __dict__: It displays the dictionary in which the class’s namespace is stored. 2. __name__: It displays the name of the class. 3. __bases__: It displays the tuple that contains the base classes, possibly empty. It displays the order in which they occur in the base class list. 4. __doc _: It displays the documentation string of the class. It displays none if the doestring isn’t y '§. _module__: It displays the name of the module in which the class is defined. Generally _ of this attribute is *__main__” in interactive mode. r fill details ;el£,name, branch, year) : Classes and Objects 224 name: Student See * Module *Student.\ noduie “) Student, bases mnt module tata ae at Pontes a Bos ets “fill details’: ) “UME detaiia’, "print details’ s Check Your Understanding 1, What do you understand by arguments “Instan ” | a ee arcturn values ces as return values”? The instances of a class can also be retuned by a function i.e. a function can return the instances ot objects. 2. Define _dict_,_bases__, _name__built-in cass attributes. Give Example. | __dict__: It displays the dictionary in which the clas __name___; It displays the name of the class. _ _bases__: It displays the tuple that contains the base classes, possibly empty. It displays them in the order in which they occur in the base class list. "s namespace is stored. | ™__name__: “,PrintStatement.__name__ = TPrintStatement “,PrintStatement. bases __ »,PrintStatement. dict __ tement.__dict_: “r § se . pasa Bee eo t'.mogule. ts) Ua matn: doc cs :7éfunction print method at 0x02CE3130>} OOP, Inheritance, generally, means to acquire the features of in ility of code. It is the capability of a class to derive the properties of ity of 222 Introduction to Computing & Problem Solving using Python '® Vehicle is.a class that is further divided into two subclasses, automobiles (driven by motors) and vehicles (driven by men). Therefore, vehicle is the base class and automobiles and pulled ve..." its subclasses. These subclasses inherit some of the properties of the base class vehicle 8 a © Truck and car are the subclasses of the class automobile that is the base class for them. The, : some of the properties of base class automobiles, Similarly, the rickshaw and bullock car..." subclasses of pulled vehicles that serves as the base class for them, The main advantage of inheritance in the context of programming is that the code can be written jn... the base class and then reused repeatedly in the subclasses. Vehicles [ Automobiles Pulled Vehicles | | ‘Truck Scooter Rickshaw Figure 8.2 Example of Inheritance Inheritance generally involves acquiring the features of a predecessor. With the help of inh can inherit a class from another class. If a class A is inherited from another class B, then class A ca the features (like variables and methods) of class B. _ The class which inherits the features of another class is known as subclass. If we want to inherit clas ‘we use the class name with the name of the class that is to be inherited in the parentheses. Classes and Objects 223 jeffill_details(seit, ya, _ Person, get_name (se) ¢ nen fame) self.branch = bra: self.year = year = details (self), ‘returns stude nt di ' ‘print (“Name: *, welhring print (“Branch: », felt be print (Year: “, self ven “year chy year): lass Teacher s Teacher (Person): turns a Teacher obj MW ieexia(sel2, nance, coe Person.get_name (self, name) H self.branch = branch t_details (self): print ("Name: * print ("Branch + self.name) “, self.branch) object for each class "= Person() | 1 = Student () | erl = Teacher() objects .get_name (‘John’) fill details(‘Jinnie’, ‘CSE’, -fill_ details (‘Jack’, ‘ECE') 2005) ‘using parent class function l.get_details()) output t1.get_details()) # Output # Output # Output get_details()) ‘Output . # output have defined a parent class Person that has two methods: get_ which has two methods: fi11_details() 11_details() and get_ ted above, We class, he student has two methods: £1 yo subclasses +h also and teacher class, whiel details () in the subclas ively. This is called inheritance. ses student and teacher to 224 ntroductionto Computing & Problem Solving using Python 8.7.1 Multiple Inheritance In multiple inheritance, a subclass is derived from more than one base classes, The subclass inherits the properties of all the base classes, In Fig, 8.3, subclass C inherits the properties of two base classes A and B, Let us look at an example: ‘There are three classes, Water animal (fish, octopus, ete.), Land Multiple Inheritance animal (Tigers, lions, ete.) and Amphibian (frog, crocodiles, ete.). Here, Amphibian is the subclass that derives the properties of the base classes, water animal and land animal, Therefore, its animals (objects) frog and crocodile live bor) on lang and water, ‘We can also define multiple inheritance in Python, When a class inherits the features of more thay «, class this is known as multiple inheritance, It is defined in the same way as inheritance. Figure 8.3 Multiple Inhertang ‘#Defining class A ‘(Defining Class B ning class c rts and B are defined and then another class ¢ is defined which chi . eet of class C is created, through which the methods of classes ** METHOD OVERRIDING mics overriding is allowed in pyr) sa the substass with differen hon. Method overri OF speci me Me al Furctiomaliny tea that the method of parent class can be method (sei) ; PANE ‘This is in pay | ¢ | ‘ChildiParent) method (self) PEINt ‘This is in cr ‘Chilay) Fmnethod () dn Child Class mn method (_init_) isa speci ole n (_init__ pecial method that is invoked when | known as the constructor method for a class. = - TA ENCAPSULATION members. This restrict the access of dat ramming Language, encapsulation is a process : internal details of an object may not be visible from oubvisle some methods which assist in accessing (hese sorts of data jm a class can be assigned in three ways i.e. public protected and privat ded by single underscore, it's assigned as a protected member, whereas if the name of a by double underscore, it ts assigned as a private member and if the name is not preceded ‘it is a public member. this concept in the given table below jon _| Behaviour an be accessed from anywhere “They are like the public members bu INS < ‘They cannot be ween and acvessed from ‘outside the class of the object definition. But he name of annot be directly accessed from outsice concept with the help of an example: RG introduction to Computing & Problem Solving using Python MyClass (object) = # defining clase det ae (welt, Xr Ye BY # public data member 4 protected data member # private data member - # Output # Output _ # Private member is not accessible - call last): line 1, in ‘object has no attribute '__ var3’ ning private member Classes and Objects 227 4.10 DATA HIDING ming, the i F ee ion To tev fae some cases when you intend to hide the attributes of objects outside iheclass Abe he visible aka Ps double score ( ___) before the name of the attributes and these attributes Wl 'Y outside the class definition, Let us understand the Python data hiding bya simple example given below: ‘class MyClass: # defining class def sum(self, increment): % self. a += increment print self. a # creating instance of class sk (most recent call last): “", line 1, in “print b._a rib : oles. MyClass instance has no attribute ‘As seen in the above example that the variable __ is not accessible as we tried to access it; the Python interpreter generates an error immediately. In such a case, the Python secures the members by internally ‘changing the names to incorporate the name of the class. If you intend to access these attributes then the ‘Syntax for accessing the variable is: ebjectName. className__attributeName -above code, if we use the aforementioned syntax to access the attributes, then the following changes sum(self, increment) : self. a += increment # creating instance of class # Accessing the hidden variable “< 228 introduction to Computing & Problem Solving using Python — Check Your Understanding 1, Define Inheritance and multiple inheritance. Give syntax for both, Ans. Inheritance . Inheritance generally means to acquire the features of something. The same is ; context of the classes. With the help of inheritance, we can inherit a class trey, Mother 4. a class A is inherited from another class B, then class A can use all the Features yy"! and methods) of class B. Wiahj ‘Syntax Class sub classname (Parent_classname) : ‘Optional Docstring’ | _ Class_suite | He meanin Multiple Inheritance We can also define multiple inheritance in Python. When a class inherits the fe ealures o than one class it is known as multiple inheritance. It is defined in the same way as inhe _ # Define your first parent class class A A "++ e2+-Class_suite.. # Define your second parent class class B class cia,B) —— —| Python Provides all the features required to support OOP, gs of 4 ps ocuse® oe Feeuses on the objects and lasses whereas procedural programmine tisa collection of data and methods, an instance of a class. Classes and Objects 229 4 Classis a set of objects that share the same attri { Data member is a variable that is def with the class or object, » Methods are the functions defi seta Ute) which can be data member and method member. either in class or in object and that holds the data associated ined in the definiti eer ndatotemen oan ecto ica, and are used by various instances of the class. 3 : ith different behaviours, this is ki i is «_ Inmethod overloading, the operations performed by the method gre aitcees as function overloading. ‘« When a class uses the characteristics of another ¢ i ‘ the process is called inheritance, lass, it is said to be a derived class or inherited class and ‘¢ When a class ited the features of more than one class, this is called multiple inheritance. ‘ Method overriding Means that the method of parent class can be used in the subclas ith diffe special functionality. gee ‘« The first argument of every method is sei. ‘¢ Objects can be used to access the attributes of the class, g o haga ee Resiou ee any point of time by making changes to its attributes. Thus, it '« The instance of a class can be passed as an argument to a function in Python. . Sermo of a class can also be returned by a function, i.e., a function can return the instances or 'e There are various built-in attributes that can be accessed with a dot operator. ¢ OBJECT: Object is a real time entity. ¥ CLASS: Classes provide the basic structure for an object. It consists of data members and method _ members that are used by the objects of the class. 7 DATA MEMBER: A variable defined either in a class or in an object, which holds the data that is Associated with the class or object. INSTANCE VARIABLE: A variable which is defined in a method and whose scope is only within the a y ‘object is an instance of the class. N: The process of creation of an object of a class. hods are the functions which are defined in the definition of class and are used by various e defined more than one time with different behaviours. DING: A function can bi : loading. The operations performed by these n overloading or method over! 230 introduction to Computing & Problem Solving using Python ¥ INHERITANCE: A class ‘A’ that can use the characteristics of another class *B’ is said to be 4 der class or inherited from ‘B’. The process is called inheritance. ¥ METHOD OVERRIDING: When the method of the parent class can be used in a subclass with dig... or special functionality, it is known as method overriding. 1. class: This is the keyword used to define a class. 2. selé: It is the first argument of every method. 3. __dict__: A class attribute that displays the dictionary in which the class's namespace is store, 4. __name__: A class attribute that displays the name of the class. 5. __bases__: A class attribute that displays the tuple containing the base classes, possibly emp 6. __doc_: Aclass attribute which displays the documentation string of the class 7. __module__: A class attribute which displays the name of the module in which the class is (REVIEW ExEReISES i ewe... PROGRAMS L Write a program that defines a class with two methods: anputStr () that will get the string using east that will print the string in upper case. Also, test the class methods >>> class UpperString (object) : def init (self): geselt.o =~” ‘def inputStr(self): _ self.o = raw input () str (self, #Input from user #Output es a class named Rectangle that takes the Parameters length and bre" 0 contain a method for computing its perimeter, f perimeter (seis); Classes and Objects 234 return Pe APECNI SOLS bev ies, ‘a = Rectangle(10,15) » print a.perimeter() output .a function that has a class an. t imal wit ak od Lag expli With a method 16 icitly with the class Dog ani Create two subclasses Tiger and id implicitly with the class Tiger. explicitly access, we need ¢ pees! Ritcciccs), © override the method in Dog class. a def legs (self): S print “legs Animal() methog” elass Dog(Animal): def legs (self): print “legs Dog() methoa” glass Tiger (Aninal): #Output #Accessing method explicitly #Output #Accessing method implicitly 1() method #output ee 1m that defines a class named Employee. Define two subclasses: Engineer and class should have a method named printDesignation() that prints Engineer for and Manager for Manager class. yee (object) : }EDesignation (self): arn “Not Known” Employee) : to Computing & Problem Solving using Python tion() #Output m. srintDesignation () cate #Output F : program to demonstrate class and their attributes _ elass Person: print “Inside the class” count = 0 init__(self, name, age, salary): ‘self.name = name self.age = age self.salary = salary erson.pcount += 1 def dispcount (self): _ print “Total number of persons”, Person.pcount def dispperson (self): __ Print “Person Name : “, self.name, “, age:”, self.age, ing objects to the class” Pie sci ecaby + 24, 2000) Pe ihect* (27, 5000) 0 o a ‘umber of person 3d” 3 Person.pcount ‘person class and _ doc: + Person. name #", Person, module _ Bi", Person. “bases _ ‘Person. “dict _ ‘tribute exists class attributes” a eson.salary ile of the permon co). ee Mone nS Olean. attributes 1 main, bases "i () , sdict + ("module +; 5 E alapooust at “On7to0batez7a5s yi roe aunt! | 2+ ‘dlapeount?s , * + ‘dimppernon’: ) deleting the atribute salary ek (most recent call last); “Person.py”, line 37, in « b. d. b. lass,’ float’> d. yFunction(): is an interesting language” b. __main__ d. Error b. d. k as an instance of class? b. Program d. Method fines objects of the same type? b, An object d. A program given declaration: blueprint that de 'b. x contains an object of square type oe “ja int vue can d. x contains a reference to a square Obje, m Which of the following ign donecizion ofa set of objects that share the same avin e _and semantics? = b, Constructor d. Method the following is responsible for initialising the objects of its class? b. Destructor d. None of the above ‘1. What is the OOP concept? Define classes and objects in Python. me Oe cscaten inheritance in Python.

You might also like