The document provides an overview of object-oriented programming in Python, explaining concepts such as classes, objects, methods, and attributes. It also discusses class creation, instance objects, garbage collection, inheritance, method overriding, operator overloading, and polymorphism. Through examples, it illustrates how Python supports these OOP principles, emphasizing the language's simplicity and adaptability.
What are Objects? •An object is a location in memory having a value and possibly referenced by an identifier. • In Python, every piece of data you see or come into contact with is represented by an object. >>>𝑠𝑡𝑟 = "This is a String" >>>dir(str) ….. >>>str.lower() ‘this is a string’ >>>str.upper() ‘THIS IS A STRING’ • Each of these objects has three components: I. Identity II. Type III. Value Arslan Arshad (2K12-BSCS-37)
Defining a Class •Python’s class mechanism adds classes with a minimum of new syntax and semantics. • It is a mixture of the class mechanisms found in C++ and Modula- 3. • As C++, Python class members are public and have Virtual Methods. The simplest form of class definition looks like this: 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑁𝑎𝑚𝑒: <statement 1> <statement 2> . . . <statement N> • A basic class consists only of the 𝑐𝑙𝑎𝑠𝑠 keyword. • Give a suitable name to class. • Now You can create class members such as data members and member function. Arslan Arshad (2K12-BSCS-37)
5.
Defining a Class •As we know how to create a Function. • Create a function in class MyClass named func(). • Save this file with extension .py • You can create object by invoking class name. • Python doesn’t have new keyword • Python don’t have new keyword because everything in python is an object. 𝑐𝑙𝑎𝑠𝑠 𝑀𝑦𝐶𝑙𝑎𝑠𝑠: “””A simple Example of class””” i=12 def func(self): return ‘’Hello World >>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠 >>> obj.func() ‘Hello World’ >>>𝑜𝑏𝑗 = 𝑀𝑦𝐶𝑙𝑎𝑠𝑠 >>> obj.func() ‘Hello World’ Arslan Arshad (2K12-BSCS-37)
6.
Defining a Class 1.class Employee: 2. 'Common base class for all employees‘ 3. empCount = 0 4. def __init__(self, name, salary): 5. self.name = name 6. self.salary = salary 7. Employee.empCount += 1 8. def displayCount(self): 9. print("Total Employee %d" % Employee.empCount) 10. def displayEmployee(self): 11. print("Name : ", self.name, ", Salary: ", self.salary) Arslan Arshad (2K12-BSCS-37)
7.
Defining a Class •The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. • Other class methods declared as normal functions with the exception that the first argument to each method is self. • Self: This is a Python convention. There's nothing magic about the word self. • The first argument in __init__() and other function gets is used to refer to the instance object, and by convention, that argument is called self. Arslan Arshad (2K12-BSCS-37)
8.
Creating instance objects "Thiswould create first object of Employee class" emp1 = Employee("Zara", 2000 ) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) • To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts. • During creating instance of class. Python adds the self argument to the list for you. You don't need to include it when you call the methods emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount 2 Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2 Output Arslan Arshad (2K12-BSCS-37)
9.
Special Class Attributesin Python • Except for self-defined class attributes in Python, class has some special attributes. They are provided by object module. Arslan Arshad (2K12-BSCS-37) Attributes Name Description __dict__ Dict variable of class name space __doc__ Document reference string of class __name__ Class Name __module__ Module Name consisting of class __bases__ The tuple including all the superclasses
10.
Form and Objectfor Class • Class includes two members: form and object. • The example in the following can reflect what is the difference between object and form for class. Arslan Arshad (2K12-BSCS-37) Invoke form: just invoke data or method in the class, so i=123 Invoke object: instantialize object Firstly, and then invoke data or Methods. Here it experienced __init__(), i=12345
11.
Class Scope • Anotherimportant aspect of Python classes is scope. • The scope of a variable is the context in which it's visible to the program. • Variables that are available everywhere (Global Variables) • Variables that are only available to members of a certain class (Member variables). • Variables that are only available to particular instances of a class (Instance variables). Arslan Arshad (2K12-BSCS-37)
12.
Destroying Objects (Garbage Collection): •Python deletes unneeded objects (built-in types or class instances) automatically to free memory space. • An object's reference count increases when it's assigned a new name or placed in a container (list, tuple or dictionary). • The object's reference count decreases when it's deleted with del, its reference is reassigned, or its reference goes out of scope. • You normally won't notice when the garbage collector destroys an orphaned instance and reclaims its space • But a class can implement the special method __del__(), called a destructor • This method might be used to clean up any non-memory resources used by an instance. Arslan Arshad (2K12-BSCS-37)
13.
Destroying Objects (Garbage Collection): ArslanArshad (2K12-BSCS-37) a = 40 # Create object <40> b = a # Increase ref. count of <40> c = [b] # Increase ref. count of <40> del a # Decrease ref. count of <40> b = 100 # Decrease ref. count of <40> c[0] = -1 # Decrease ref. count of <40>
14.
Class Inheritance: • Insteadof starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name. • Like Java subclass can invoke Attributes and methods in superclass. class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite Syntax • Python support multiple inheritance but we will only concern single parent inheritance. Arslan Arshad (2K12-BSCS-37)
Overriding Methods: • Youcan always override your parent class methods. • One reason for overriding parent's methods is because you may want special or different functionality in your subclass. class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method Arslan Arshad (2K12-BSCS-37)
17.
Overloading Operators: • Inpython we also overload operators as there we overload ‘+’ operator. class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) Print(v1 + v2) Arslan Arshad (2K12-BSCS-37)
18.
Method Overloading • Inpython method overloading is not acceptable. • This will be against the spirit of python to worry a lot about what types are passed into methods. • Although you can set default value in python which will be a better way. • Or you can do something with tuples or lists like this… Arslan Arshad (2K12-BSCS-37) def print_names(names): """Takes a space-delimited string or an iterable""" try: for name in names.split(): # string case print name except AttributeError: for name in names: print name
19.
Polymorphism: • Polymorphism isan important definition in OOP. Absolutely, we can realize polymorphism in Python just like in JAVA. I call it “traditional polymorphism” • In the next slide, there is an example of polymorphism in Python. • But in Python, Arslan Arshad (2K12-BSCS-37) Only traditional polymorphism exist?
20.
Polymorphism: Arslan Arshad (2K12-BSCS-37) classAnimal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Mistoffelees'), Dog('Lassie')] for animal in animals: Print(animal.name + ': ' + animal.talk())
21.
Everywhere is polymorphismin Python • So, in Python, many operators have the property of polymorphism. Like the following example: Arslan Arshad (2K12-BSCS-37) • Looks stupid, but the key is that variables can support any objects which support ‘add’ operation. Not only integer but also string, list, tuple and dictionary can realize their relative ‘add’ operation.
#6 C++ is a complicated beast, and the new keyword was used to distinguish between something that needed delete later and something that would be automatically reclaimed. In Java and C#, they dropped the delete keyword because the garbage collector would take care of it for you. The problem then is why did they keep the new keyword? Without talking to the people who wrote the language it's kind of difficult to answer. My best guesses are listed below: It was semantically correct. If you were familiar with C++, you knew that the new keyword creates an object on the heap. So, why change expected behavior? It calls attention to the fact that you are instantiating an object rather than calling a method. With Microsoft code style recommendations, method names start with capital letters so there can be confusion. Ruby is somewhere in between Python and Java/C# in it's use of new. Basically you instantiate an object like this: f = Foo.new()It's not a keyword, it's a static method for the class. What that means is that if you want a singleton, you can override the default implementation of new() to return the same instance every time. It's not necessarily recommended, but it's possible.
#12 Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute: __dict__ : Dictionary containing the class's namespace. __doc__ : Class documentation string or None if undefined. __name__: Class name. __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode. __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.